Returning true vs returning 1, would this affect performance?

Feb 2, 2016 at 9:17pm
I'm grading someone's code.

They are returning a bool but their code says return 1 rather than return true

1
2
3
4
5
6
7
8
9
10
11
 /*******************************************
 * Queue :: EMPTY
 *******************************************/
template <class T>
bool Queue <T> :: empty() const
{
   if (numItems == 0)
      return 1;
   else
      return 0;
}


Is this a bad practice? On the one hand, you are doing an implicit casting, which I feel like is sorta slow.

On the other hand, bool is such a small data type I wonder if casting it is rather inexpensive. Should I tell these guys to not return an int or to just let this code be?
Last edited on Feb 2, 2016 at 9:18pm
Feb 2, 2016 at 9:35pm
The performance difference is likely completely negligible, although I've never benchmarked it. This is more a question of style than performance. Stylistically I'd prefer to return true or false when the function return type is bool.
Feb 2, 2016 at 9:47pm
Why not just return numItems == 0; to avoid both implicit conversions and redundant code and, to appease some purists, multiple exit points?

In any case, the compilers aren't that dumb: this function compiles into two CPU instructions on intel cpus: testl or cmpl followed by sete or cmove, depending on the compiler. Using true/false instead of 1/0 does not change the code.
Last edited on Feb 2, 2016 at 9:49pm
Feb 2, 2016 at 9:53pm
In any case, the compilers aren't that dumb: this function compiles into two CPU instructions on intel cpus: testl or cmpl followed by sete or cmove, depending on the compiler. Using true/false instead of 1/0 does not change the code.

Thanks!
Topic archived. No new replies allowed.