Home > Software engineering >  C99 standard: is the logical negation operator defined to also operate directly on a function?
C99 standard: is the logical negation operator defined to also operate directly on a function?

Time:10-11

I am curious if there is any difference between assigning the output of a function foo() to a variable and then prefixing the logical negation ! operator vs. prefixing the logical negation operator directly before the function. i.e. is

int output = foo();
if(!output){

}

formally equivalent to:

if(!foo()) {

}

CodePudding user response:

This probably isn't what you're thinking of, but it is a difference between your two example code fragments, and an important one: in

int output = foo();
if (!output) {
   ...
}
...

the variable output, and therefore the value returned from the function, is available to code both inside and below the if-statement. In your other example, the value returned from the function is not available to anything but the ! operator inside the if-condition.

This is probably the most important practical reason to choose one form or the other; do you need that value for anything besides the if-condition? If so, you need the variable.

CodePudding user response:

Other than the difference mentioned by @zwol, there is no logical difference. The expression ! foo() is processed as "call foo()" then "negate the return value".

Doing output = foo(); then ! output does "call foo()" then "save the return value in variable output" then "negate the value in output". Same result.

In fact, a compiler might optimize away the variable output - depending on the context.

  • Related