Reputation: 1041
Suppose I have this piece of C code here:
int main() {
int a = 10;
printf("test1");
printf("test2");
someFunc();
a = 20;
printf("%d",a);
}
Well I think that all these statements are stored on the stack at a time and then popped one by one to get executed. Am I correct? If not, please correct me.
Upvotes: 1
Views: 129
Reputation: 214395
The C standard doesn't specify where things go in memory.
However, computers work like this in general:
.data
, .bss
, .rodata
, .stack
, .text
and there is possibly also a .heap
. The .text
section is for storing the actual program code, the rest of the sections are for storing variables. More info on Wikipedia..text
section, which is read-only memory. So for your specific code snippet, the only thing that is stored on the stack is the variable a
. Or more likely, it is stored in a CPU register, for performance reasons.
The string literals "test1"
, "test2"
and "%d"
will be stored in the .rodata
section.
The literal 20
could either be stored in the .rodata
section, or more likely, merged into the code and therefore stored in .text
together with the rest of the code.
The program counter determines which part of the code that is currently executed. The stack is not involved in that what-so-ever, it is only for storing data.
Upvotes: 2
Reputation: 7352
Whats worth noting is that the C standard does not mandate implementation. So as long as the output is correct according to the standard, the compiler is free to implement this as it choses.
What most likely happens for you is that the compiler translates this bit of C into assembler code which is then executed top to bottom.
a = 20;
Is most likely optimised out unless you use it somewhere else. Good compilers also throw a warning for you like:
Warning: Unused Variable a
Upvotes: 1
Reputation: 234785
Not really no. The C standard doesn't mention a stack so your notions are ill-conceived.
A C compiler (or interpreter for that matter) can do anything it likes so long as it follows the C standard.
In your case, that could mean, among other things, (i) the removal of a
altogether, since it's only used to output 20 at the end of the function, and (ii) someFunc()
could be removed if there are no side effects in doing so.
What normally happens is that your code is converted to machine code suitable for the target architecture. These machine code instructions do tend to follow the code quite faithfully (C in this sense is quite "low level") although modern compilers will optimise aggressively.
Upvotes: 6