Consider this:
main()
{
int i = 1;
fork(); fork(); fork();
printf("%d ",i);
}
The output of the above code is:
1 1 1 1 1 1 1 1
That is, at the end there are 8 (2^3) processes reaching the printf()
line. Now consider the code below:
main()
{
int i = 1;
fork() && fork() || fork();
printf("%d ",i);
}
Initially, I thought there'd be no change in the output because the results of the comparisons using &&
, ||
are not being evaluated by a control statement like if
or while
. That is, they're being discarded. However, The output of this code is:
1 1 1 1 1
Meaning, at the end there are 5 processes that reach the printf()
line.
My question: What does this line do
fork() && fork()||fork();
Definitely, something has changed. I've never contemplated using comparison operators like &&
, ||
without control statements like if
, while
to evaluate the result of the comparison and accordingly take some action. I thought, without these control constructs, the comparison operators are meaningless; they'd simply return 1
or 0
without anything being done about it.
Clearly, I'm mistaken, and am totally unaware of this usage of the operators.