I am a complete beginner in C++. i recently came across a piece of code. I don't seem to understand the use of ? and :. can anyone tell me how it works? why we use ? and :
CODE
(j==1 or i==s)?(cout<<"* "):((j==i)?(cout<<" *"):(cout<<" "));
It is a ternary operator. The conditional operator is kind of similar to the if-else statement as it does follow the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible.
Syntax: The conditional operator is of the form.
variable = Expression1 ? Expression2 : Expression3 It can be visualized into if-else statement as:
if(Expression1) { variable = Expression2; } else { variable = Expression3; } Ternary operator
A ternary operator evaluates the test condition and executes a block of code based on the result of the condition.
Its syntax is:
condition ? expression1 : expression2; Here, condition is evaluated and
if condition is true, expression1 is executed.
And, if condition is false, expression2 is executed.
You can find a example here https://www.programiz.com/cpp-programming/ternary-operator
It is a short circuit test condition if/else, then put the assign value.
void Main() { // ****** Example 1: if/else string result = ""; int age = 10; if(age > 18) { result = "You can start college"; } else { result = "You are not ready for college"; } // ****** Example 2: if/else with short circuit test condition result = (age > 18) ? "You can start college" : "You are not ready for college"; }
variable = test ? valueiftrue : valueiffalse. Can be nestedvariable = test ? (test ? valueiftrue : valueiffalse): (test ? valueiftrue : valueiffalse). Shouldn't be nested