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

Conditional OR statement

Just wondering what the syntax would be for a multiple conditional OR statement when comparing strlen to various lengths from a header file.

Just wondering if this is correct.
if( strlen( a ) != b || c || d )
{

}

Let me know if I’ve misunderstood or missed and parentheses I might have needed.

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

>Solution :

This will give you the correct answer, but it won’t work the way you think it will.

Conditions are evaluated individually. This means that for the following code :

char* a = "test";
int b = 2;
int c = 3;
int d = 4;
if(strlen(a) != b || c || d )
{
   …
}

… will do the following :

if((4 != 2) || (3) || (4))

Since positive integers are evaluated as true :

if((true) || (true) || (true))

Which evaluates as true.

What you really want there is the following :

if((strlen(a) != b) || (strlen(a) != c) || (strlen(a) != d))
{
   …
}

Or, for a better optimized version :

int len = strlen(a);
if((len != b) || (len != c) || (len != d))
{
   …
}

EDIT :

As it was pointed out in the comments, what you really want to validate here is if a string length isn’t one of three things. So what you need is the AND operator.

int len = strlen(a);
if((len != b) && (len != c) && (len != d))
{
   …
}
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