That's the ternary operator. It works as an if else statement.
- Code: Select all
if(var==0) { r=0; } else { r=255; }
(var==0) ?(r=0) : (r=255);
/*(condition) ? this : otherwise this; */
As you can see it is a mini if/else. It can be used to shorten code when dealing with simple if/else, but I don't recommend doing anything complex with it for the same reason I don't recommend using condition && code.
Hblade wrote:Is that a good use of the var==0 && code idea?
I would say no, on the grounds that you'd be teaching the same bad habit, and you are demonstrating code to other people. When you write code for others, you should keep it as clean and direct as possible. You don't see people using that very often in C, because it isn't common practice.
There is nothing wrong with using if statements. On the occasion that they can be avoided by cleaning up your program's structure, you should. But if an if statement makes sense logically, and you aren't relying on complex branching because of if statements, then you shouldn't make your code more complex by avoiding it. An example would be using prime numbers so you can use a switch, instead of using an if.
Now, another thing. You use this.
- Code: Select all
fm >= 1 && fm--;
Which would be just as easily done by doing this.
- Code: Select all
fm-=(fm>=1);
They do the same thing, and it is clearer what the second one is doing than the first one. Also you were just asking about that.