regarding this code:
#include <stdio.h>
int main(){
int x = 1;
if (0 == fork()){
int x = x 1;
fork();
}
else{
int x = 4 * x;
fork();
}
printf("%d",x);
}
Some friends of mine told me that the result should be 2244
, but when I try and run it, I get 1111
.
Can you please help me understand how to fork()
works here, and which answer is correct?
Thanks a lot!
CodePudding user response:
The only thing that gets printed is x
in the outermost scope of the main
definition. It is 1, so only “1” is printed, once by each of the four processes created.
Inside the inner blocks, int x = …;
creates a new object distinct from the outer x
even though they have the same name. These objects are not printed, so their values are irrelevant.
In more detail, in int x = x 1;
, the x
in the initializer refers to the x
being declared, so this definition attempts to use the object in its own initialization. The behavior of this is not defined by the C standard,1 so the program would be permitted by the standard to go horribly astray here. However, typical compilers implement some simplistic code here, either ignoring the initialization since it is essentially meaningless or implementing the x 1
using whatever bits happen to be already in the memory allocated for the new x
. int x = 4 * x;
has the same problem.
Footnote
1 Due to C 2018 6.3.2.1 2, which says the behavior is not defined when the value is used of an uninitialized automatic object whose address is not taken.