Home > Enterprise >  is if(s.length()) saying that if it returns a value, proceed?
is if(s.length()) saying that if it returns a value, proceed?

Time:03-03

Typically, I see code with say if(s.length() > 1) ..., but here it only has if(s.length()).

The length function is implemented as mentioned below. When used in the test3 function call within the file containing int main(), is if(s.length) saying that if it returns a count that is greater than zero then it will execute the body of that if statement?

int statistician::length() const
{
    return count;
}

Code (test3() call in int main()):

statistician s, t, u, v;

if (s.length( ) || t.length( )) return 0; // <-- HERE
if (s.sum( ) || t.sum( )) return 0;

t.next(5);
u.next(0); u.next(10); u.next(10); u.next(20);

v = s   s;
if (v.length( ) || v.sum( )) return 0;
v = s   u;
if (!(u == v)) return 0;
v = t   s;

CodePudding user response:

In c an int can be implicitly converted to a bool. The rule is:

int (0) -> false
int (anything else) -> true

In your case, the length will return some positive number if it exists, and 0 if it doesn't so this logic:

if (s.length())

Is equivalent to

if (s.length() >= 1)
               ^ // Very important, you probably missed this, but you probably
                 // want to know if the string is greater than 0, not "2 or more"

for the way you have probably implemented it. However! int can also be negative, and negative values are still not 0, and therefore also will be true. So if your function was something like this:

int length() {
   if (some condition) {
       return -1; // error code
   }
   return count;
}

Then your if statements are suddenly not equivalent. So, ... best thing to do if this is not the case, is to represent your data as you intend it. AKA, if your count value can't be negative, then do not allow it to be. Use an unsigned int, or size_t:

size_t length();
  •  Tags:  
  • c
  • Related