-6

Can I directly use a comparison as an integer in C++?

For example, can I do this?

int var = 0;
for (i=0;i<20;i++){
    var += (int)(var < 10);
}

In theory, this will increase var up to a value of 10. I know that it works in Python.

uzumaki
  • 1,743
  • 17
  • 32

1 Answers1

1

Yes, C++ has implicit casting from bool to int.

However, I would suggest you make this a bit more clear that this is your actual intention, so that future readers understand your intent. Explicitly cast it to an int first.

int var = 0;
for (i = 0; i < 20; i++) {
    var += (int)(var < 10);
}
Software2
  • 2,358
  • 1
  • 18
  • 28
  • 4
    why not make it even more explicit and use an if statement? – xaxxon Jul 20 '17 at 23:54
  • It can potentially be slower. An if statement is a potential branching code point. Modern processors may attempt branch prediction. Simply explicitly casting the intended type will produce the same compiled code as the implicit cast, however. Of course, it's an absolutely minimal optimization. If your audience would better understand your code with a few extra if statements, I'd always go for the more readable/understandable code. – Software2 Jul 20 '17 at 23:56
  • In this case, it seems the if statement is faster since the compiler can know to abandon the loop when var becomes greater than 10. https://godbolt.org/g/PZ1jDn In the code as written in the answer, it always performs 20 iterations. – xaxxon Jul 21 '17 at 04:20