# How to read the expression (i = j) || (j = k)

This is a discussion on How to read the expression (i = j) || (j = k) within the C Programming forums, part of the General Programming Boards category; I was practicing some exercise from the book, so I wrote down the program below. Code: #include<stdio.h> int main(void) { ...

1. ## How to read the expression (i = j) || (j = k)

I was practicing some exercise from the book, so I wrote down the program below.

Code:
```#include<stdio.h>

int main(void)
{
int i = 7, j = 8, k = 9;

printf("%d ", (i = j) || (j = k));
printf("%d %d %d", i, j, k);

getch();
return 0;
}```
The result should be 1 8 8 9, but I don't know how this expression work.
How to interpret the expression (i = j) || (j = k)?
In the first parentheses (i = j), did the program assign 8 to i?
If so, why didn't it assign 9 to j as well, in the second parentheses (j = k)?
Later on, why the i remain as 8, when was it saved?

2. Ok, this is about the way C evaluates logical or ...

It will look at (i = j) || (j = K) only far enough to decide if one OR the other is true... left to right i = j will assign the value of j to i ... this will always result in true, so it never tests the second set of braces and thus never assigns j = k.

The I will remain 8 because you used assignment (single equal sign) not comparison (double equal sign). That is to say that ...
Code:
```if (i = j)
printf ("Hello");```
... assigns the value of j to i and will always be true (because it succeeded) and it will always print "Hello".

However...
Code:
```if (i == j)
printf("Hello");```
... only if the value of i is the same as the value of j ... neither value is changed.

Try your original code with double equals ( == ) in that first printf() call ... it should print 1789 instead.

3. Why is i = j will always be true?

4. Originally Posted by Roger Lo
Why is i = j will always be true?
It's a standard set by ANSI C. Anything not 0 is true. This world is full of standards and conventions which sometimes make sense, sometimes don't.

5. > ... assigns the value of j to i and will always be true (because it succeeded) and it will always print "Hello".
It only succeeds because j is non-zero.
If j was zero, then the assignment would still happen, but the logical side effect (the implied (expr) != 0) is false.

6. Originally Posted by Roger Lo
Why is i = j will always be true?
See Salem's post... I should qualify my statement to say that "in your example" it will always be true.
As Salem points out, if j is 0, it will evaluate to false...
Another way of breaking it down to understand it is...
Code:
```i = j;
if ( i != 0 )
Printf("Hello");```

7. understood, thanks for everyone!

Popular pages Recent additions