Why does this C code compile?

房东的猫 提交于 2021-02-07 11:18:16

问题


#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?


回答1:


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.




回答2:


Your guess is exactly right. int c pushes space onto the stack for the variable, which is then read from and re-written to for the c = c part (although the compiler may optimize that out). Your compiler is pushing the value on as 0, but this isn't guaranteed to always be the case.




回答3:


It's undefined behavior to use an uninitialized value (§C99 J.2 "The value of an object with automatic storage duration is used while it is indeterminate"). So anything can happen from nasal demons to c = 0, to playing Nethack.




回答4:


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.




回答5:


The C specification don't assure that variables will be initialized to 0, 0.0 nor "" or ''.

That is a feature of compilers and never you must thrust that will happen.

I always set my IDE/Compiler to warning about that.



来源:https://stackoverflow.com/questions/3239386/why-does-this-c-code-compile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!