LEARNER
LEARNER

Reputation: 123

priority of operators in C language

Hi I'm learning C language and I have learned that () have more priority than && in C, but when I execute the following program, a gard it's value although that it has been placed between () can I get any explanation please ?

#include<stdio.h>
int main()
{
    int a,b;
    a=2,b=4;
    printf("%d\n",0&&(a=b));
    printf("%d",a);
    return 0;
}

Upvotes: 0

Views: 253

Answers (2)

John Bode
John Bode

Reputation: 123458

The && and || operators both short-circuit - that is, if the value of the expression can be determined from the left operand, then the right operand will not be evaluated at all.

Given the expression a && b, if a evaluates to 0 (false), then the value of the entire expression will be false regardless of the value of b, so b isn't evaluated.

Given the expression a || b, if a evaluates to non-zero (true), then the value of the entire expression is true (1) regardless of the value of b, so b is not evaluated.

In your example, 0 && (a=b), the left operand is 0, so the expression will evaluate to 0 (false) regardless of what happens with (a=b), so (a=b) is not evaluated.

Upvotes: 1

Iipal
Iipal

Reputation: 87

It's because when the left-most statement in logical && is false, then right-most statement will not be calculated\executed.

Upvotes: 3

Related Questions