0

What does this code mean?

int c, sign;

sign = (c == '-') ? -1 : 1;

I only know integers as numbers. What do the question mark etc. mean?

BeldCode
  • 67
  • 1
  • 7

1 Answers1

2

This is the ternary operator.

sign = (c == '-') ? -1 : 1;

and the code above is equivalent to

if(c == '-') sign =-1;
 else sign=1;

To explain more about the ternary operator :

the syntax is :

(condition)? do this if condition is true:do this if condition is false

Another example you can use it for :

   int a=1;
   printf( "Value of test is %d\n", (a == 1) ? 20: 30 );

this will print 20 if a==1 is true and 30 if a==1 is false

Spinkoo
  • 2,080
  • 1
  • 7
  • 23