变量的编译时初始化如何在 c 内部工作?

Nik*_*mar 6 c

编译时初始化仅在我们在变量声明期间为变量赋值时才发生。更具体地说,声明期间int a=2和声明后初始化变量有什么区别int a; a=2

klu*_*utt 6

在声明期间int a=2和声明之后初始化变量有什么区别int a; a=2

不同之处在于第二个不是初始化。这是一个任务。当涉及到您非常简单的示例时,实践中没有区别。

结构体和数组

一个很大的区别是一些初始化技巧在常规赋值中不可用。例如数组和结构初始化。您将需要 C99 或更高版本。

int x[5] = {1, 2, 3, 4, 5}; // Ok
x = {1, 2, 3, 4, 5};        // Not ok

struct myStruct {
    int x;
    char y;
};

struct myStruct a = {1, 'e'};     // Ok
a = {1, 'e'};                     // Not ok
a = (struct myStruct) {1, 'e'};   // But this is ok
struct myStruct b = {.y = 'e'};   // Also ok
b = (struct myStruct) {.y = 'e'}; // Even this is ok
b = {.y = 'e'};                   // But not this
Run Code Online (Sandbox Code Playgroud)

你可以用一个小技巧来分配数组。您将数组包装在一个结构中。但是,我不建议为此目的。这不值得。

struct myArrayWrapper {
    char arr[5];
};

struct myArrayWrapper arr;
arr = (struct myArrayWrapper) {{1,2,3,4,5}}; // Actually legal, but most people
                                             // would consider this bad practice 
Run Code Online (Sandbox Code Playgroud)

常量变量

如果你已经声明了一个变量,const那么你以后不能改变它,所以它们“必须”被初始化。

const int x = 5; // Ok
x = 3; // Not ok, x is declared as const
const int y;     // "Ok". No syntax error, but using the variable is 
                 // undefined behavior
int z = y;       // Not ok. It's undefined behavior, because y's value
                 // is indeterminate
Run Code Online (Sandbox Code Playgroud)

常量变量并不是严格要求初始化的,但如果你不初始化,它们就会变得毫无价值。

静态变量

它还以一种特殊的方式影响静态变量。

void foo() {
    static int x = 5; // The initialization will only be performed once
    x = 8;            // Will be performed everytime the fuction is called
Run Code Online (Sandbox Code Playgroud)

因此,如果此函数之前已被调用,则该函数将返回 1,否则返回 0:

int hasBeenCalled() {
    static int ret = 0;
    if(!ret) {
        ret = 1;
        return 0;
    }
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

关于静态变量的另一件事是,如果它们没有显式初始化,它们将被初始化为零。局部变量(具有自动存储的变量)将包含垃圾值。另外,请注意全局变量是自动静态的。

static int x; // Will be initialized to 0 because it's static
int y;        // Is also static, because it's global
auto int z;   // Not ok. You cannot declare auto variables in global space

int main(void)
{
    int a;        // Will be auto as b
    auto int b;   
    static int c; 
    
    int d;
    d = a;        // Not ok because b is not initialized.
    d = b;        // Not ok
    d = c;        // Ok because static variables are initialized to zero
    d = x;        // Ok
    d = y;        // Ok
Run Code Online (Sandbox Code Playgroud)

在实践中,你永远不会auto在 C 中使用关键字。实际上,没有任何情况下auto使用它是合法的,auto如果你省略它,它不会默认使用。这不是真的static

您可以在 C 标准的第 6.7.9 章中阅读有关初始化的信息。作业在第 6.5.16 章中找到