Aman Singh
Aman Singh

Reputation: 21

What does a : mark in C mean?

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

Answers (3)

ryyker
ryyker

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 than 5, then set y equal to 3, else set y equal to 4.

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

dreamcrash
dreamcrash

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

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

It's a ternary operator or conditional operator.

Upvotes: 0

Related Questions