Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

I have marked the code in question with ‘/****/’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int statistician::length() const
{

    return count;

}

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

statistician s, t, u, v;


if (s.length( ) || t.length( )) return 0; /****/
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;

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading