Question mark statement

Time:2021-4-28
#include<iostream>

using namespace std;

int main(void)

{

    int a = -1;

    a > 0 ? a = a : a = -a;

    cout << a;

    return 0;

}

The output is 1

Question mark statement means whether the statement before the question mark is true. If it is true, the statement before the colon will be executed. Otherwise, the statement after the colon will be executed.

There must be a statement before and after the colon. Don’t think that you can empty it without executing it. For example, delete a = A and empty it. This is not good. If you want to empty the statement, you can write a 1 or something, such as

#include<iostream>

using namespace std;

int main(void)

{

    int a = -1;

    a > 0 ? 1 : a = -a;

    cout << a;

    return 0;

}

The value of the question mark statement

If the value before the question mark is true, the value of the question mark statement is equal to the value of the statement before the colon, otherwise it is the value of the statement after the colon

#include<iostream>

using namespace std;

int main(void)

{

    int a = -1;

    int b = a > 0 ? 2 : a = -a;

    cout << a << endl << b;

    return 0;

}

output
1
1
The value of a = – A is the value of a after being assigned.

#include<iostream>
using namespace std;
int main(void)
{
    int a = 1;
    int b = a > 0 ? 2 : a = -a;
    cout << a << endl << b;
    return 0;
}

output
1
2