"?"的含义在代码中

时间:2016-03-05 15:40:13

标签: c++

"是什么?"在这段代码中意味着什么?

#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;
}

1 个答案:

答案 0 :(得分:0)

奇怪的格式化。 ?是条件/三元运算符。它的工作方式类似condition ? if_true : if_false,它测试条件,然后执行这两个表达式中的一个。

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

这只是一种糟糕的写作方式:

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

当然,如果你在这里使用?,最好写一下:

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

cout语句将在任何一种情况下发生,因此将其移出条件会使其更具可读性。

此运算符适用于此类小条件,但如果它在两个不同的表达式之间进行决策,最好使用if

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

if (row == col) //good
    cout << '*';
else
    some_function();
相关问题