user3437460
user3437460

Reputation: 17454

Logical operator with Arithmetic operator in C

I came across a question and I wanted to verify whether my assumptions were correct.

Given the following codes:

1.    int i = -2, j = 1, ans;
2.    ans = i++ || ++j;
3.    printf("%d %d %d", i,j, ans);

The output is: -1 1 1

In C language, it seems that only 0 will be treated as false, any other values will be treated as true when used with a logical operator. So I am not doubtful why ans derives to 1 (true || true gives us true(1) )

What I wanted to ask here is: Why is the value of j still 1 and not 2 despite ++j? Can safely assume that any arithmetic operations after the logical operators || && will only be effective at the line it is used(in this case, line 2), and after which the variable still retain its original value?

Upvotes: 1

Views: 199

Answers (3)

Himanshu
Himanshu

Reputation: 4395

As in Second Line of your Code i.e

ans = i++ || ++j;

first it will check i++ as it is not zero that means it is true. And in OR Condition if first condition is true it will not check second condition i.e ++j.

Because if first condition is true is doesn't matter, Second condition is TRUE or FALSE it will return a true value. So if First Condition is true it will not check the other condition.

Upvotes: 1

Crowman
Crowman

Reputation: 25908

Logical operators short circuit. That is, in the following:

ans = i++ || ++j;

++j will never be evaluated if i++ evaluates to true (non-zero).

Upvotes: 0

Anbu.Sankar
Anbu.Sankar

Reputation: 1346

|| operator wont do any operation on second operand when first operand is nonzero.

Because, any one of the operand is non-zero then, output will be true in || operator operation. In your code 1st operand is non-zero. Thats why operation on second operand is not performed.

Upvotes: 2

Related Questions