0

Is it correct to compare bool to 1?

In a legacy code I find often:

if (xyz.isCounterActive() == 1)

where sCounterActive() returns bool.

Obviously, if ( xyz.isCounterActive() ) is sufficient, but If I change this, I don't know which side-effects it may cause. Software is big, buggy but the customer insists, that it is working.

Compiler is VS2008

Valentin H
  • 7,240
  • 12
  • 61
  • 111

1 Answers1

1

In this case result of xyz.isCounterActive() will be implicitly converted to int. There're many rules of implicit conversion, which can be found here, for example.

Probably signature of isCounterActive changed since it was introduced, and the one, who changed it, forgot to modify all isCounterActive calls.

Community
  • 1
  • 1
ujohnny
  • 111
  • 1
  • 2
  • The first part is misleading, as the answer in fact seems quite simple (see the link I've posted under the question). As for the second part, integers were once commonly used in place of booleans, so it's more probable it is the original signature and usage of this function. Such "idioms" are very common in legacy code. – BartoszKP Sep 23 '15 at 09:21
  • I don't see any significant difference between the integral promotion described in your linked answer and the implicit conversion mentioned above. Integral promotion is more specific, but this hardly seems misleading. – Useless Sep 23 '15 at 09:26
  • @Useless It's misleading in the sense that it suggests that you need to decipher these complex rules to get the answer, whereas the linked answer gives it *directly* in plain text as a quotation from the standard. – BartoszKP Sep 23 '15 at 09:30
  • Oh, I see what you mean. Yes, in that sense it would be clearer to focus on integral promotion rather than lumping it in with all possible implicit conversions. – Useless Sep 23 '15 at 09:31
  • Yes! I think this is the case. The original programmer was a C programmer and has not realized, there is bool in C++. One can clearly see his evolution of learning C++ during the 5 years :-) – Valentin H Sep 23 '15 at 09:34