Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any significance to this return statement?

I was wondering if there was any significance in a part of a code I am seeing that involves

return (num!=0);

where num is an int. And this is the return statement of a boolean function that wants to return TRUE if num != 0, and false if num = 0.

I am not sure if there is an hidden significance to this, but I am not seeing why they cannot just simply write:

return num;

Here is the code I saw:

bool SemClass::cut(int &a, int &b, int &c) 
{
  int num = 0;    
  check(a, num);
  check(b, num );
  check(c, num);
  return (num != 0);
}
like image 672
roulette01 Avatar asked Jan 07 '23 15:01

roulette01


1 Answers

The value 0 for integral, floating-point, and unscoped enumeration and the null pointer and the null pointer-to-member values become false when returned as a boolean by implicit conversion. Other values such as 1, 2, 3, 4 etc. map to true. This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.

Implicit conversions: en.cppreference.com/w/cpp/language/implicit_cast

In this case, in C++, writing num and num!=0 are both fine. However, num!=0 might make it more obvious that the method is returning a boolean. Technically, only an integer of value 0 would equate to a boolean false, while all other values would equate to a boolean true. By writing num!=0, It is made explicit that the method would return true if num is not equivalent to 0 and false if it is.

Good practice dictates that if it's a genuine truth value, then you should use a boolean as it makes it very clear to the caller what will be returned. When returning an integer, it could be seen as a code/enum type value.

Therefore, num!= is preferred to num in this case. The brackets are not required however. Some compilers will also issue a warning if you return an integer when the method is supposed to return a boolean.

like image 112
Tacocat Avatar answered Jan 14 '23 17:01

Tacocat