-1

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<<" "));

Abhinav K
  • 87
  • 5
  • https://stackoverflow.com/questions/68017734/c-ternary-operator-with-equality-statement - `variable = test ? valueiftrue : valueiffalse`. Can be nested `variable = test ? (test ? valueiftrue : valueiffalse): (test ? valueiftrue : valueiffalse)`. **Shouldn't be nested** – Caius Jard Jun 25 '21 at 04:45
  • 1
    Does this answer your question? [How do I use the conditional (ternary) operator?](https://stackoverflow.com/questions/392932/how-do-i-use-the-conditional-ternary-operator) – 김선달 Jun 25 '21 at 05:03

3 Answers3

1

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;
}
Nirav Vikani
  • 118
  • 8
0

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

0

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";
    
}
Thomson Mixab
  • 657
  • 4
  • 8