-3

How the Output was 1 and 4 . I cant understand the logic behind the c program?

#include <stdio.h>

int main()
{
    int a;
    int i = 4;
    a = 24 || --i;
    printf("%d %d",a,i);

    return 0;
}

Output

1 4

...Program finished with exit code 0
Press ENTER to exit the console.

Can anyone explain the logic for the program..........

Magesh 1
  • 11
  • 4

3 Answers3

2

I think that the language C has 0 as the value for false and all non-zero numbers as true.

So, from the viewpoint of an optimising compiler you get:

a = 24 || --i;
a = TRUE OR --i;

=> "TRUE OR ..." is always TRUE, so just skip it!
Hence: 
a == 1 (which means "TRUE")

And what about i? Well, nothing happened, so it just keeps having its original value.

Dominique
  • 16,450
  • 15
  • 56
  • 112
2

Lazy evaluation. Take a look at this line:

a = 24 || --i;

the || operator first evaluates the left hand side operand. If it evaluates to true then the right hand side of it won't get evaluated, as it doesn't matter.

Now, why is a actually 1? As a matter of fact, it's a version of true since it's the result of a boolean expression and it is cast from bool to int upon assignment, resulting in a value of 1. The i prints 4 because the --i isn't executed.

yoniyes
  • 1,000
  • 11
  • 23
1
a = 24 || --i;

|| is the logical or.

A 24 is true (not 0). Therefore the second Part of the Or (--i) will be skipped.

There is no need to evaluate it, as the first part is already found to be true. So i will NOT be decremented and stay at 4

ttm02
  • 61
  • 4