ganesh
ganesh

Reputation: 23

Confusion with usage of Increment Operator

I am learning C. I came across the following program -

#include <stdio.h>

int main() {
  int var1 = 2, var2 = 6;
  var2 = var2 || var1++ && printf("Computer World");
  printf("%d %d\n", var1, var2);
  return 0;
}

After compilation with gcc 4.4.5 on Ubuntu 10.10, I'm getting the output as -

2 1

I understand how 'var2' is set to 1.

Even thought there is a increment operator on 'var1', why it is not incremented when we see the console output?

Upvotes: 1

Views: 107

Answers (2)

Lee Duhem
Lee Duhem

Reputation: 15121

In C, || is a shortcut operator, which means in an expression such as exp1 || exp2, if the truth value of this expression can be determined by evaluating exp1, exp2 would not be evaluated.

For example, in your case, the result of evaluating var2 is 6, which is true in C, so other part of the expression, which is var1++ && printf("Computer World"), would not be evaluated.

You can see Shortcut Operators for further details.

Upvotes: 0

MOHAMED
MOHAMED

Reputation: 43518

var2 || var1++ && printf("Computer World");

is a logic operation so if the var2 is true (var2 is not equal to zero) then the second logic operation var1++ && printf("Computer World"); will not be executed (It's called a short-circuit operation) . So that's why the var1 is not incremented

Try to inverse your logic operation in this way and you will get the var1 incremented:

var2 = var1++ && printf("Computer World") || var2;

Upvotes: 3

Related Questions