'I'm confused about why pid isn't printed as expected in fork()

I'm currently learning System Programming course and I'm a little confused about how fork() works.

void fork0()
{
    int pid;
    if (pid = fork() == 0) {
        printf("c : %d\n", pid);
        printf("Hello from child\n");
        exit(0);
    }
    else {
        printf("p : %d\n", pid);
        printf("Hello from parent\n");
        wait(NULL);
    }
}

In this simple snippet of code, I get the following output :

p : 0
c : 1
Hello from child
Hello from parent

I thought fork() returns 0 to child process and the PID of child process to parent process. But why does printf() inside the child process, print 'pid' 1? And why does printf() inside the parent process print 'pid' 0? I would appreciate any help.. thanks!!

c


Solution 1:[1]

In C, == operator has higher precedence than = operator.

Therefore, pid = fork() == 0 will assign the comparision result of fork() == 0 to pid.

In the parent process, the return value of fork() won't be zero, so the comparision result to be assigned will be 0.

Add parenthesis like (pid = fork()) == 0 to firstly assign the return value of fork() to pid and then compare the value with zero.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MikeCAT