as we see there is no use of “i” in program but still effect on program,and i know that num is not initialized that’s why i want to know the effect and output
Besides the fact that num
is uninitialized and hence results in undefined behaviour (means, anything can happen), you can have a look at the technical aspects by analysing the assembly output. However this is byond the C specification and heavily depends on the compiler, the underlying architecture and the operating system you are using.
-
How does
i
affect the program?It is not used and hence the compiler might even decide to completely ignore it. However, when compiling the code with
gcc
with no optimization, we see that this adds one instruction to the code:movl $-4, -12(%rbp)
Hence, there are two effects: The resulting object code will be slightly larger due to the additional instruction, and the runtime of the program will be increased slightly. This might be completely different if you are using a different optimization level.
-
Num is not initialized that’s why i want to know the effect and output
For automatic variables, only space is allocated (on the stack), but it is not initialized. Since the same memory locations (the stack) might have been used before, these locations might have any contents. So, the output depends on what happened before, and this is indeterminate. Since
j
is calculated based onnum
, also the contents ofj
is undefined. -
why the output is getting effected when i remove the variable i
Removing the variable
i
might affect the space allocation on the stack (since less space is required), and might result innum
to reuse a different memory location which might contain by chance a constant value instead of a random value. However, still this is undefined and changes with compiler, architecture and platform, and depends on what happened earlier.Possible stack layout with
i
, by chance the first word always contains0x0000
while the second word is different for each program invocation:-------- | 0x0000 | <= memory location assigned to i (will be initialized to -4 in the next step) +--------+ | 0xnnnn | <= memory location assigned to num (contains a random value) --------
Possible stack layout without
i
:-------- | 0x0000 | <= memory location assigned to num (randomly "initialized" to 0x0000 by coincidence) +--------+ | 0xnnnn | (Unused) --------
Still, everything which we observe is simply Undefined Behaviour.
1
solved What is happening with this code [closed]