0
#include <stdio.h>
int main()
{
    int a = 1;
    int b = 1;
    int c = a || --b;
    int d = a-- && --b;
    printf("a=%d, b= %d, c= %d, d= %d",a,b,c,d);
    return 0;
}

In th above code, I expected output to be a=0, b= -1, c= 1, d= 0 but the output was a=0, b= 0, c= 1, d= 0

Screenshot_VS Code

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Prithvi Reddy
  • 11
  • 1
  • 5
  • Don't code that way. Such code is unreadable, and you will be in trouble understanding it the next month. Consider using [GCC](http://gcc.gnu.org/) as `gcc -Wall -Wextra -g` to compile your code, and also use [the clang static analyzer](https://clang-analyzer.llvm.org/) on your code – Basile Starynkevitch Feb 09 '21 at 07:57
  • 1
    Please do not add pictures of your code or your output if it is only plain text. – Gerhardh Feb 09 '21 at 08:12

1 Answers1

1

In the expression used as an initializer in this declaration

int c = a || --b;

as the operand a is not equal to 0 then the expression --b is not evaluated.

So the variable c is initialized by 1.

From the C Standard (6.5.14 Logical OR operator)

4 Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to 0, the second operand is not evaluated.

In the expression used as an initializer in tjis declaration

int d = a-- && --b;

the operand a-- is not equal to 0 (the value of the postfix operator is the value of its operand before decrementing). So the operand --b is evaluated. As its value is equal to 0 then the variable d is initialized by 0.

From the C Standard (6.5.13 Logical AND operator)

4 Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.

As a result a and b will be equal 0 after this declaration.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335