Reputation: 21
void main()
{
int x,y;
scanf("%d", &x); <-1
y=(x>5?3:4);
printf("%d",y); ->4
}
What is the use of: in y=(x>5?3:4);
?
Upvotes: 1
Views: 175
Reputation: 23236
"What is the use of : in y=(x>5?3:4); ?"
:
represents the shorthand version of the else
clause of an if-then-else
expression when using the C ternary operator. So in your example:
y = (x>5 ? 3 : 4);
The English expression could be stated as:
if
x
is greater than5
, then sety
equal to3
, else sety
equal to4
.
The traditional long version in C syntax would use the expression sequence:
if(x > 5)
{
//true path
y = 3;
}
else
{
//false path
y = 4;
}
Upvotes: 2
Reputation: 51603
It is known as ternary operator. This:
y= (x>5 ? 3 : 4);
means if x
is greater than 5, to y
will be assigned the value 3
, otherwise (x
is less or equal to 5) the value 4 will be assigned to y
. That code is semantically the same as:
if(x > 5)
y = 3;
else
y = 4;
you can find a more in-depth explanation here.
Upvotes: 4