here is the code:
int main(int argc, char *argv[ ]){
int x = 33;
if(!fork()){
int x = 10;
printf("%d\n", x);
}
fork();
printf("%d\n", x);
return 0;
}
i would assume that because the value of int changes for the original child, it carries the value of 10 and in the second fork as well(fork();), so the original child and its child print 10 so the output is like this: 33 33 10 10 10 But it seems that although the value of int changes inside the if, the child then gets back the original value of x which is 33 and both print 33 after the second fork(so the output is like this: 33 33 10 33 33. Why is that?(i believe \n doesnt have anything to do with it) here is a photo of what i think is happening but apparently it doesnt
The x
printed in the first printf
inside the if
block is defined with a local scope that ends at the }
. The second printf
uses the x
defined in the scope of the main
body that still has the initial value 33
.
Redefining a variable in a local scope with the same name as one define in an enclosing scope is called shadowing. It is confusing and error prone and will be reported with a warning if you enable advanced compiler warnings with -Wall -Wextra
or -Weverything
.
Here is a modified version that should produce output closer to your expectations:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int x = 33;
if (!fork()) {
x = 10;
printf("%d\n", x);
}
fork();
printf("%d\n", x);
return 0;
}
This version should print 33
twice and 10
three times in an unpredictable order.
The original version posted in the question should print 33
4 times and 10
just once in an unpredictable order.