How does this compile? I forgot to set my second condition in my second for loop and it compiles.

    if(cmp_str5 == 0 || cmp_str6 == 0)
    {
        if(cmp_str5 == 0 || cmp_str6)

Recommended Answers

All 3 Replies

It compiles so ship it?

Compilers can't mind read yet so logic errors compile without any feedback to you.

This is C code? Assuming it is and assuming cmp_str5 and cmp_str6 are both integers, this

if(cmp_str5 == 0 || cmp_str6 == 0)
{
    if(cmp_str5 == 0 || cmp_str6)

would be the same as this:

if(cmp_str5 == 0 || cmp_str6 == 0)
{
    if(cmp_str5 == 0 || cmp_str6 != 0)

Both are perfectly legal code, but would optimize to this:

if(cmp_str5 == 0 || cmp_str6 == 0)
{
    if(cmp_str5 == 0)

And if there are no else if or else statements anywhere below, it would optimize to this:

if(cmp_str5 == 0)

Compiling without optimization would add a few bytes (I don't know how many) to the compiled object code, plus a very slight increase at runtime if it needlessly evaluated an expression. Running it on a regular computer or a modern phone or even on one of the larger microchips, the difference would be negligible, but I've programmed some of the smaller microchips where every single byte counted (i.e. the executable had to be 16K or even less) and the compiler was sometimes smart enough to catch and throw out the unnecessary comparisons. Java compilers catch unreachable statements and potentially uninitialized references, so potentially, with the right flags and the right compiler, the compiler would hopefully issue a warning for code such as yours, but it wouldn't issue an error because your code is perfectly legal. If you tell the compiler to treat warnings as errors, it would issue an error.

In boolean expressions, any non-zero value evaluates as True. Zero evaluates as False so

if(cmp_str5 == 0 || cmp_str6)

actually means

if cmp_str5 is zero or cmp_str6 is not zero

That's how loops like while (*w) work for strings.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.