-3

What does "?" mean in this code?

#include <iostream>
using namespace std;

int main ()
{
    int size;
    cout<<"Enter size: ";
    cin>>size;
    for (int row=1; row<=size;row++)
    {
        for (int col=1; col<=size;col++)
            (row==col)?                 <------------------ this is what i mean
            cout <<"*":cout<<" ";
        for(int col=size-1;col>=1;col--)
            (row==col)?
            cout <<"*":cout <<" ";
        cout <<endl;
    }
    return 0;
}
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
  • Look up ["ternary operator"](https://en.wikipedia.org/wiki/%3F:). `(condition) ? (true-part) : (false-part)`. Then don't use it unless you absolutely have to. – DevSolar Mar 05 '16 at 15:43
  • basically a short if-else clause. – Hatted Rooster Mar 05 '16 at 15:44
  • Very ugly and hard to read. Never use the conditional operator for side effects. – Christian Hackl Mar 05 '16 at 15:46
  • 1
    @DevSolar: " don't use it..." - I have heard this very often and absolutely disagree. This operator is for conditional **assignment** and if you have a conditional assignment it is a very clear and concise way of expressing what's going on. I think it is its misuse, as in this code sample, that gave it its bad reputation. But when used correctly it is a helpful language feature. – Frank Puffer Mar 05 '16 at 15:59

1 Answers1

0

It's weird formatting. ? is the conditional/ternary operator. It works like condition ? if_true : if_false where it tests the condition, and then executes one of those two expressions.

(row==col)?
cout <<"*":cout<<" ";

Is just a bad way of writing:

(row == col) ? (cout << "*") : (cout << " ");

Of course, if you're going to use ? here, it's better to write:

cout << (row == col) ? '*' : ' ';

The cout statement is going to happen in either case, so moving it outside the conditional makes it a lot more readable.

This operator is good for small conditionals like this, but if it is deciding between two different expressions, it is better to use an if.

(row == col) ? (cout << '*') : (some_function()); //bad

if (row == col) //good
    cout << '*';
else
    some_function();
Weak to Enuma Elish
  • 4,622
  • 3
  • 24
  • 36