21
#include <stdio.h>
int main() {
    int c = c;
    printf("c is %i\n", c);
    return 0;
}

I'm defining an integer variable called c, and I'm assigning its value to itself. But how can this even compile? c hasn't been initialized, so how can its value be assigned to itself? When I run the program, I get c is 0.

I am assuming that the compiler is generating assembly code that is assigning space for the the c variable (when the compiler encounters the int c statement). Then it takes whatever junk value is in that un-initialized space and assigns it back to c. Is this what's happening?

4

5 回答 5

30

I remember quoting this in a previous answer but I can't find it at the moment.

C++03 §3.3.1/1:

The point of declaration for a name is immediately after its complete declarator (clause 8) and before its initializer (if any), ...

Therefore the variable c is usable even before the initializer part.

Edit: Sorry, you asked about C specifically; though I'm sure there is an equivalent line in there. James McNellis found it:

C99 §6.2.1/7: Any identifier that is not a structure, union, or enumeration tag "has scope that begins just after the completion of its declarator." The declarator is followed by the initializer.

于 2010-07-13T16:50:36.210 回答
11

你的猜测完全正确。int c将空间推送到变量的堆栈上,然后从该部分读取并重新写入该c = c部分(尽管编译器可能会对其进行优化)。您的编译器将值推送到 as 0,但不能保证总是如此。

于 2010-07-13T16:52:29.847 回答
5

使用未初始化的值是未定义的行为(§C99 J.2“具有自动存储持续时间的对象的值在不确定时使用”)。因此,从鼻恶魔到 c = 0,再到玩 Nethack ,任何事情都可能发生。

于 2010-07-13T16:51:21.347 回答
2

c has been initialized!

Although this is one line of code, it is in fact initializing c first, then assigning c to it. You are just lucky that the compiler is initializing c to zero for you.

于 2010-07-13T16:48:34.077 回答
2

C 规范不保证变量将被初始化为 0、0.0 或 "" 或 ''。

这是编译器的一个特性,你永远不必推动它会发生。

我总是将我的 IDE/编译器设置为对此发出警告。

于 2010-07-13T18:27:57.750 回答