Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this C code compile?

Tags:

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

like image 551
Vivin Paliath Avatar asked Jul 13 '10 16:07

Vivin Paliath


People also ask

Why does C need to be compiled?

C is a mid-level language and it needs a compiler to convert it into an executable code so that the program can be run on our machine.

What does C code compile to?

A compiler translates the C program (source code) into machine language (machine code) which it stores on the disk as a file. This process of converting the source code into machine code is known as compilation.

Why do we compile our code?

Because computer can't understand the source code directly. It will understand only object level code. Source codes are human readable format but the system cannot understand it. So, the compiler is intermediate between human readable format and machine-readable format.


2 Answers

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.

like image 191
Brian R. Bondy Avatar answered Sep 24 '22 03:09

Brian R. Bondy


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.

like image 24
me_and Avatar answered Sep 26 '22 03:09

me_and