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

标签 c

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

最佳答案

What is the difference between initializing variable during declaration int a=2 and after declaration 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

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

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 

常量变量

如果你已经将一个变量声明为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

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

静态变量

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

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

所以如果之前调用过这个函数将返回 1,否则返回 0:

int hasBeenCalled() {
    static int ret = 0;
    if(!ret) {
        ret = 1;
        return 0;
    }
    return 1;
}

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

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

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

您可以在 chapter 6.7.9 中阅读有关初始化的内容在C标准中。分配可在 chapter 6.5.16 中找到

关于c - 变量的编译时初始化如何在 c 内部工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56512652/

相关文章:

将 C 代码编译为静态库以在 iPhone 应用程序中使用?

c++ - 是否有一个宏来检查给定函数是否存在

c - 段错误(转储核心)

c - [QuickSort]递归问题

c - 如何将c代码映射到postgres c函数格式?

c - 在 linux 中静态链接库

c++ - 如何读取 PRS/SKmapDat 文件?

c - 将数组中的元素作为指针传递给 C 中的函数

使用 64 位 GCC 在 Cygwin 上编译 64 位 GSL

c++ - 将 std::map 移植到 C?