what does ...?... :... mean in C++, is it same as IF THEN ELSE?
it is a shorthand way of assigning values to variables. e.g. x = (i > 1) ? 10 : 100; means assign the value 10 to x if i is greater than 1, otherwise assign the value 100 to it. without this you would have to write the longer set of statements: if (i > 1) { x = 10; } else { x = 100; }
so why do we need IF THEN ELSE
if then else is more readable for things like this: if (i > 0) { printf("I am greater than 1"); doStuff(i); doMoreStuff(); } else { printf("I am not worthy of any calculation!"); }
there are more things which can be made in different ways but same result
for example?
goto?
it's called the ternary operator and as you said it works similar to IF THEN ELSE. Syntax: <condition>?<statement if true>: <statement if false>
for while
The ternary operator/conditional expression is an expression, so it can be used right after a return statement int abs(int num) { return num < 0 ? -num : num }
oh thats cool
the if-else clause can execute blocks of statements if (expression) { // statements } else { // statements } The ternary operator cannot (only takes in expressions like a normal operator).
You can chain ternary operators too (but people will hate you!) int compare(int a, int n): return a < 0 ? -1 : a > 0 ? 1 : 0;
bad example, but you get the idea :-D
oh that is a terrible expression to chain ternary operator
Although the ternary operator is the same (in the simple case) as an if else statement, if the results of the conditional are blocks of code, if else is a better choice. The if else structure also has the feature of if, else if, else which the ternary operator doesn't. The else if stuff also leads to basically the same question between if, else if, else and switch statements.
@rsmith you can chain ternary operators to achieve the same effect as if, else if, else
What CAN be done isn't necessarily what you'll be able to figure out three months from now when you maintain the code.
right :-D if-else blocks are much more readable, although ternary operators make code very concise.
i heard story that one student so fell in love with ternary operators that he wrote ALL conditional code with nested things and then he got job and he was writing everything with it too and at some point he left job leaving all his written code with ternary operators and no one could manage it so had to rewrite :D
Join our real-time social learning platform and learn together with your friends!