antox antox - 4 years ago 113
C Question

Which are the executable statements?

Many times, reading around, I found definitions like this one:


Definitions are not executable statements. They’re messages to the compiler. For example, the definition
int i;
simply tells the compiler the type of variable i and instructs the compiler to reserve space
in memory for the variable.


Statements like this one leave me always confused, because, IMHO, everything can be seem as "requiring an action". For example, in this case, the computer has to perform some actions to allocate some memory.

So what are those statements really referring to?

Answer Source

Compilers translate the C language into machine code, which can be executed by the CPU. It's often easy to see which bytes of machine code correspond to which statements in your C code. Debuggers use this correspondence when showing how your C code runs.

So the meaning of "a declaration is not an executable statement" is that no machine code corresponds to a declaration. This also means that:

  • CPU doesn't spend any time to "run" the declaration (but the compiler does spend time to examine it)
  • A visual debugger will "skip" the declaration when running your program step by step

You can see this in the online compiler explorer, which does this for C++, but it's close enough to C. It paints each line of code in a different colour to visualize which lines generate which machine code. An example from there:

Input C/C++ code

int square(int num)             // painted in white
{                               // painted in teal
    int result;                 // painted in white
    result = num * num;         // painted in yellow
    return result;              // painted in gray
}                               // painted in red

Output assembly code (represents machine code)

square(int):
        push    rbp                          // painted in green
        mov     rbp, rsp                     // painted in green
        mov     DWORD PTR [rbp-20], edi      // painted in green
        mov     eax, DWORD PTR [rbp-20]      // painted in yellow
        imul    eax, DWORD PTR [rbp-20]      // painted in yellow
        mov     DWORD PTR [rbp-4], eax       // painted in yellow
        mov     eax, DWORD PTR [rbp-4]       // painted in gray
        pop     rbp                          // painted in red
        ret                                  // painted in red

You can see that lines painted in white (declarations) "don't generate code", and "are not executable statements".

BTW note that definitions, unlike declarations, are "executable", in the sense described above. For example:

int x = 0; // declaration and definition; the definition is "executable"
int y = x * (x + 1); // the definition here does non-trivial work
int z; // only declaration; not "executable"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download