I have no idea what the question mark does here.
Why not simply writeCode:cout << bit? "1": "0";
Would that not be the same thing?Code:cout << bit;
I have no idea what the question mark does here.
Why not simply writeCode:cout << bit? "1": "0";
Would that not be the same thing?Code:cout << bit;
if the bit is an int but can only be one or zero, then I suppose the output would be the same. But are you asking what the '?' does? That's the tertiary operator. It is basically an "if/else" on the condition to the left of it.
"You are stupid! You are stupid! Oh, and don't forget, you are STUPID!" - Dexter
It's called the ternary operator. It's not quite the same thing in this case as bit is more than likely a bool type, while "1" and "0" are strings (character if had been '1'). The effect is the same, however, visually. Programmers like to use it... makes us feel good, I guess.
It would make more sense if the example was:
Then you'd get either of the messages printed depending on whether bit is true (non-zero) or false (zero).Code:cout << bit? "I am non-zero": "nothing here";
I might be wrong.
Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
This:
for explanation purposes, would be better wrtten as:Code:out << bit? "1": "0";
If "bit" is true, then the expression after the ? will be evaluated.Code:out << bit ? "1" : "0";
If "bit" is false, then the expression after the : will be evaluated.
Mainframe assembler programmer by trade. C coder when I can.
Ternary operators often lead to sloppy looking code. So just be certain you make their use clear.
Example:
Nasty... With some proper tabbing and multi-lining it may be acceptable, however typically for stuff like this more often you may want to consider using a switch case statement instead.Code:int getRed(int color, int colorFormat) { return (colorFormat == RED8GREEN8BLUE8)?color & 0xFF:(colorFormat == RED5GREEN6BLUE5)?color & 0x5:(colorFormat == RED10GREEN12BLUE10)?color & 0x3FF:0; }
As a person who does like some of the more nasty options available in C++ syntax, I do like to issue conventional wisdom about how to not do as I do. Though I do crazy stuff that would drive you up the wall, Elysia, I do it in a very readable and understandable way.