I am a fairly beginner programmer in C, and I had always assumed that the way variable declaration worked was that when you declare a variable like int x;
, you were telling the compiler to set aside memory for that variable, which would then be initialised if you then wrote something like x = 3;
, and that perhaps the compiler might shuffle that declaration to somewhere more efficient if it can when compiling.
However I recently read that this is not what happens. So what happens, and why? Does something concrete happen behind the scenes, or are declarations effectively just messages to the compiler with no analogue in the eventual binary that it spits out? And how does all this apply to function declarations?
C
, there may be "analogue in a binary" for declarations. The standard does not impose any constraints. But yes, what you said is true for most compilers. There are no instructions that actually create memory for a variable. It is just a "message" to the compiler that there exists a variablex
in the program. Store it wherever you see it fit. The actual instructions you will see will be the first time that variable is used. Again, this is true for most compilers.