What will be the output if in the following condition, funct() function fails and returns 1 or -1 accordingly, Where funct() returns 0 for success and an error code on failure?

for(int i = 0; i < 2; i++)
  if(nError = funct() != 0)
    printf("Error code %d\n",nError);

Though function funct() returns -1 but error code will be 1 for both the cases.

Here is the explanation:
condition funct() != 0 is true or 1 as funct() returns -1
result is nError = 1
This is because expressions are evaluated from right to left. Thus funct() != 0 is the first to be evaluated and the result is passed on to the left side.
If we need the return/error code in nError, we must enclose the statement in brackets like:
(nError = funct()) != 0

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

 Vote 0

Similar topics related to this section

if, if-else, if-else-if, label and goto, switch case, compare with ==, execution sequence, loop statements, for, while, do-while loop syntax, for to while,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan