-1

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;
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
beps
  • 47
  • 7

1 Answers1

4

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;
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • thanks, this was exactly what I was looking for – beps Aug 27 '16 at 15:03
  • btw is this faster method for processor what you posted compared to my if()?my brother gave me a "challenge" to program an app that works efficiently on 486 PC in DOS – beps Aug 27 '16 at 17:29