-2

If an integer is uneven (odd), I would like to get the previous number, otherwise I would like to keep the current number. E.g. if x = 3, I would like to assign 2 to x, if x = 4, then nothing happens.

At the moment, I do the following: x = (x/2)*2, but I have heard that division is computational expensive. Does -O3 optimize this expression? I am using the c++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4 compiler. x is a uint32_t.

YnkDK
  • 681
  • 9
  • 26

1 Answers1

2

Try the following

x &= ~1;

I suppose that x is declared as having type int. Otherwise if the rank of type x is greater than the rank of type int then you should use an integer literal of the type of the variable x.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335