Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why `(a-- > 0)` and `((a--) > 0)` are same?

Tags:

c++

c

operators

The program is as

main()
{
int a=1;
if( a-- > 0)
   printf("AAAA");
else
   printf("BBBB");
}

Its output is AAAA and if I use

main()
{
int a=1;
if( (a--) > 0)
   printf("AAAA");
else
   printf("BBBB");
}

then why again the output is AAAA. () has more preference then -- .

like image 778
Gaurav Avatar asked Dec 22 '22 18:12

Gaurav


2 Answers

The postfix operator -- has higher precedence than any boolean comparison operator.

What do you expect exactly? a-- always evaluates to the value of a which is decremented after evaluation.

like image 86
Benoit Avatar answered Jan 07 '23 18:01

Benoit


The postfix -- operator returns the original value of the variable, even after decrementing it.

So yes, a is decremented before the comparison, but the result of the expression a-- is not a, but the value 1.

like image 44
David Tang Avatar answered Jan 07 '23 18:01

David Tang