[Solved] How can I replace this code with one if statement? [closed]


Without knowing why you want to use a single if, it’s hard to tell. Of course, you can use ternary operators without any ifs:

unsigned int x, y;
cin>>x;
y = x<=1
? 1
: x<=3 
    ? 2
    : x<=5
      ? 3
      : 6;

Or ugly boolean casting hacks for exactly one if (please don’t actually do this outside of a puzzle or codegolf context):

unsigned int x, y;
cin>>x;
if (x<=5) {
    y = 1 + (int)(x == 2 || x == 3) + (int)(x == 4 || x == 5);
} else {
    y = 6;
}

Or, if you insist on exactly one if:

unsigned int x, y;
cin>>x;
if (x <= 5) {
   y = x/2 + 1;
} else {
   y = 6;
}

@Pietrek’s answer shows you the better variant with a ternary operator (slightly modified here):

unsigned int x, y;
cin>>x;
auto const cutoff = 6;
y = x < cutoff ? x/2 + 1 : cutoff;

Note that in any case x >= 0 is always true when working with unsigned data types, so I omitted it.


If this is not purely a puzzle challenge but actual production code, please use the last example and make the number 6 a const or constexpr with a meaningful name.

2

solved How can I replace this code with one if statement? [closed]