beps beps - 3 months ago 5
C++ Question

Shorter method for assigning value conditionally

I don't really know the term and don't know with what keywords I could search this, but is there a way to optimize (sort of make it shorter), basically this code?

//int y (1 or 2)
int x = 1;
if(y == 2) x = 2;


I remember seeing something with bool but can't remember what it was, but it used "?" (question marks in the code to check if something is something)
How I'd make that shorter too without extra lines of code?

//bool y (true or false)
bool x = true;
if(y) x = false;

Answer

What you mean should be ternary operator.

The ternary operator is of the form: condition ? if_true : if_false. You can apply it like this:

int x = (y == 2 ? 2 : 1);

bool x = (y ? false : true);

for the latter code, it can simply be

bool x = !y;
Comments