• Create Account

Posted 16 January 2013 - 11:41 PM

I've always heard and known of the conditional operator in C++ though for some reason my brain would always forget exactly how it's read.  I decided to take a quick look at it again as I do see some places in my code that is a lot longer than it should be just because I always used a full if/else statement to do one quick test. I just wanted to ask to make sure I am reading these right.

lets say I have the following:

// assume x has already been declared and defined earlier in the program.
int a = (x > 100) ? 0 : 1;

This would read and be the same as:

// again assume x is defined and declared earlier in the program
if(x > 100)
a = 0;
else
a = 1;



I just want to make sure I am right in reading this.  Even though I do feel dumb that I have always forgot about this operator.

So in other words really if the first expression in true, then the second expression is executed.  If the first expression is false then the third expression is executed.  Right?

Posted 16 January 2013 - 11:39 PM

I've always heard and known of the conditional operator in C++ though for some reason my brain would always forget exactly how it's read.  I decided to take a quick look at it again as I do see some places in my code that is a lot longer than it should be just because I always used a full if/else statement to do one quick test. I just wanted to ask to make sure I am reading these right.

lets say I have the following:

// assume x has already been declared and defined earlier in the program.
int a = (x > 100) ? 0 : 1;

This would read and be the same as:

// again assume x is defined and declared earlier in the program
if(x > 100)
a = 0;
else
a = 1;



I just want to make sure I am right in reading this.  Even though I do feel dumb that I have always forgot about this operator.

PARTNERS