A Misunderstanding About Logical Operators
1 min read
This page was translated by AI
While doing an assignment today, I ran into this problem:
Write a program that accepts three integers and outputs the largest one.
I wrote:
`#include <stdio.h>
int main(){ int a,b,; scanf(“%d %d %d”,&a,&b,&c); if(a>b>c||a>c>b){ printf(“max=%d”,a); } if(b>a>c||b>c>a){ printf(“max=%d”,b); } if(c>a>b||c>b>a){ printf(“max=%d”,c); } }`
But this was the result:
I had misunderstood how logical operators work.
In fact, a > b > c does not compare all three values at once. It is evaluated according to operator precedence and associativity: first, a > b is evaluated and produces a Boolean result (0 or 1), then that result is compared with c.