Chinmay Joshi
Chinmay Joshi

Reputation: 56

Behavior of Conditional Operator in arithmetic operation

This question is about how conditional operator works in arithmetic operation and assignment statement.

Tested on gcc, arm-gcc.

//gcc 5.4.0

#include  <stdio.h>

int main(void)
{
    printf("Hello, world!\n");
    int temp=70;
    int t2=temp%100 + temp>99?2000:1900;
    printf("t2=%d",t2);
    return 0;
}
//This code returns answer 2000.
//gcc 5.4.0

#include  <stdio.h>

int main(void)
{
    printf("Hello, world!\n");
    int temp=70;
    int t2=temp%100 + (temp>99?2000:1900);
    printf("t2=%d",t2);
    return 0;
}
//This code returns answer 1970.
//gcc 5.4.0

#include  <stdio.h>

int main(void)
{
    printf("Hello, world!\n");
    int temp=70;
    int t2= temp>99?2000:1900 +temp%100;
    printf("t2=%d",t2);
    return 0;
}
// Answer is 1970
//gcc 5.4.0

#include  <stdio.h>

int main(void)
{
    printf("Hello, world!\n");
    int temp=70;
    int t2= 5+ temp>99?2000:1900 +temp%100;
    printf("t2=%d",t2);
    return 0;
}
// Answer is, 1970!

Once arithmetic statement encounters conditional operation, it ignores left part of statement. (I think anything after conditional operation in order of execution is ignored)

Also, we can mitigate this by using round brackets (), or having conditional operation at left most. Can anyone explain this behavior? Is there any undefined behavior problem introduced by using conditional operation inside arithmetic statement?

Also surprised that this is not being asked before. If it is, please provide link. Thanks a lot!

Upvotes: 1

Views: 117

Answers (2)

JonatanE
JonatanE

Reputation: 941

The value of t2 is dependent on the operator precedence of the modulus %, addition + and ternary ?: operators.

You can find the full list of C operator precedence by following this link.

In your case, the modulus operator has highest precedence, followed by addition and then the ternary operator.

Upvotes: 3

abelenky
abelenky

Reputation: 64720

Case 1: int t2=temp%100 + temp>99?2000:1900; be re-written for clarity as: int t2=(temp%100 + temp)>99 ? 2000 : 1900;

And that expression: temp%100 + temp is 140, which is bigger than 99, so the expression has value 2000.


Case 2: int t2=temp%100 + (temp>99?2000:1900);

temp is not GreaterThan 99, so the expression is 1900, and added to temp%100, resulting in 1970


Case 3: int t2= temp>99?2000:1900 +temp%100;

temp is not GreaterThan 99, so the expression is 1900+70, resulting in 1970


This is all Order of Operations; just as * and / take precedence over + and -, all operators have a precedence.

Upvotes: 2

Related Questions