cc89ansi-c

Combining comparison tests within a control flow statement in ANSI C


I am trying to remember if, using a standard c compiler (C89), the two if statements below will evaluate in the same way.

snippet 1:

boolean function(formattype* format)
{
    if(format != null && (*format == format1 || *format == format2 || *format == format3) )
        return true;
    else
        return false;
}

would evaluate in the same way as snippet 2:

boolean function(formattype* format)
{

    if(format != null && (*format == format1 || format2 || format3) )
        return true;
    else
        return false;
}

I am only interested in the evaluation of the second comparison and I only added the function for illustration purposes. I seem to remember using some similar method to evaluate the == using each of the ||'d arguments without typing them all out but cannot remember the specifics.

Edit: Perhaps the function made things more confusing than it did help illustrate.

I am trying to evaluate the following

if(format != null && (*format == format1 || *format == format2 || *format == format3) )

The first is just a check to prevent de-referencing a null pointer, so ignore it. The second three are seeing if the de-referenced format pointer is equal to any of the three different format types (they are in an enum if you must know).

I do not want to use a macro, I want to simplify the comparison. It may not be possible, I simply have a vague memory of performing a similar operation.

I thought it was something along the lines of the second example.

if(format != null && (*format == format1 || format2 || format3) )

Solution

  • No it won't. While the first check is valid, the second will give you an erronous result. It basically means: "If (*format equals format1) OR (format2 is nonzero) OR (format3 is nonzero)" - assuming that either of format2 or format3 is nonzero, this will always evaluate to true.

    You probably meant to tamper with bitwise operators. If format 1, 2 and 3 are different powers of two, then you can check whether *format is one of them using

    if (*format & (format1 | format2 | format3))
    

    not the bitwise (as opoosed to logical) AND and OR operators. However, this approach is not safe - it'll evaluate to true even if the memory pointed to by format is the sum of some of the format 1, 2 and 3 constants (assuming formattype is an integral type).