-3

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.

jarmod
  • 71,565
  • 16
  • 115
  • 122
  • 3
    Not aware of any programming language where this would work. Save the length in a variable and compare that variable value with `if (len != b && len != c && len != d)` – jarmod Jul 21 '23 at 15:07
  • 1
    if you want to evaluate whether `strlen(a)` is not equal to `b`, `c`, or `d`, this isn't going to do it. For one thing, you're only comparing `strlen(a)` to `b`. `c` and `d` are not being compared to `strlen(a)`. Further, unless `b,` `c`, and `d` have the same value, `strlen(a)` is guaranteed to be not equal to at least one of them. That's why jarmod used `&&` instead of `||` because what you really want to say is that `strlen(a)` is not equal to *all* of them. – erik258 Jul 21 '23 at 15:08
  • Ok that makes sense thanks guys – SaintCorVic Jul 21 '23 at 15:23
  • @jarmod Python's `if len(a) not in (b, c, d):` has a similar intent – Pete Kirkham Jul 21 '23 at 15:24
  • 1
    @PeteKirkham yes, but the closer analogy in Python is the [very common mistake](https://stackoverflow.com/questions/15112125) of writing `if type == "cat" or "dog" or "mouse":` or `if a or b or c == 0:` – jarmod Jul 21 '23 at 15:38

1 Answers1

3

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))
{
   …
}
MartinVeronneau
  • 1,296
  • 7
  • 24