Operator Precedence - Expression Evaluation - c

For the following code snippet I get the output as 1. I want to know how it came?
void main()
{
int x=10,y=20,z=5,i;
i=x<y<z;
printf("%d",i);
}

i=x<y<z;, gets interpreted as i=(x<y)<z, which in turn gets interpreted as i=1<z, which evaluates to 1.

10 is less than 20, resulting in 1, and 1 is less than 5, resulting in 1. C doesn't chain relational operators as some other languages do.

It operates as follows:
Since < is a logical expression, x<y i.e 10<20 is true i.e 1. So it becomes 1<z i.e 1<5 which is again true i.e. 1 which is assigned to i. So i is 1.

This is because your code evaluates as:
void main()
{
int x=10,y=20,z=5,i;
i=((x<y)<z); //(x<y) = true = 1, (1 < 5) = true
printf("%d",i);
}

what output did you want?
In C,
i = 2 < 3; //i == 1.
i = 4 < 3; //i == 0.
If condition evaluates to false, value returned is 0, and 1 otherwise.
Also, x < y < z will be evaluated as ((x < y) < z).

x<y // 1 as (10 < 20) will return 1
result of(x<y)<z // 1 as (1<5) will return 1

C++ doesn't support multi-part comparisons like that.
x < y < z
is interpreted as
(x < y) < z
or that is, determine if x < y, then see if that boolean is less than z.
There's some discussion on why that is over at the software engineering StackExchange.
When you find yourself trying to do this, instead you need to write it as two separate comparisons joined by a boolean:
(x < y) && (y < z)

Related

how does c evaluate less than and more than expretion? [duplicate]

This question already has answers here:
Chaining multiple greater than/less than operators
(6 answers)
Closed 9 months ago.
I would like to know how i is evaluated in this code in C language ?
int x = 10, y = 20, z = 5, i;
i = x < y < z;
printf("%d\n",i);
The result of a relational operator is either integer 1 if the condition is true or 0 otherwise. And relational operators evaluates from left to right.
So this statement
i = x < y < z;
is equivalent to
i = ( x < y ) < z;
and as x is less than y then it can be also rewritten like
i = 1 < z;
that initialize the variable i by 1 because 1 is less than 5.
From the C Standard (6.5.8 Relational operators)
6 Each of the operators < (less than), > (greater than), <= (less than
or equal to), and >= (greater than or equal to) shall yield 1 if the
specified relation is true and 0 if it is false.107) The result has
type int.
If you will rewrite the statement like
i = x < y && y < z;
then the result of the expression will be equal to 0 because y is not less than z.

Why is if (2 < 9 < 3) true?

This was a question in my preparation exam:
int val = 0;
int x = 0;
int y = 1;
if (x < val < y)
printf(" true ");
else
printf(" false ");
Why is this true? I tried changing x and val and it ignored those changes, as long as y was larger than 0 (so 1, 2, 3...) the statement was true. So for example: if (3 < 9 < 2) will be true.
( 2 < 9 < 3 ) is evaluated as ( ( 2 < 9 ) < 3).
In the first step 2 < 9 is evaluated to be true, which is represented as integer value 1 and results in ((1) < 3) for the second step.
That is obviously true.
You probably wanted something like ((x < val) && ( val < y)).
The first is check whether x < value. If true, it return 1 so the next is check whether 1 < y.
First you check x and val. If its value is correct, you convert it to 1 and check it with y.
If you build with -Wall option using GCC compiler you will get a warning like this:
<source>:7:11: warning: comparisons like 'X<=Y<=Z' do not have their mathematical meaning [-Wparentheses]
if (x < val < y)
Detailed explanation of this warning can be found in GCC documentation. The relevant part is as following:
-Wparentheses
...
Also warn if a comparison like x<=y<=z appears; this is equivalent to (x<=y ? 1 : 0) <= z, which is a different interpretation from that of ordinary mathematical notation.
...
NOTE: Comparisons in C follow the left to the right approach. (if all operators are of same priority)
Thus, evaluation of (2 < 9 < 3) will be done in 2 steps:
step 1. evaluation of (2 < 9): it is true, thus, integer value=1.
step 2. evaluation of ( (2 < 9) < 3 ) i.e (1 < 3): it is also
true.
I think you wanted (2 < 9) && (9 < 3).
In C, usually operators follow left to the right approch(except operators like =, -=, +=, etc.). Operator <, > follows left to the right approch too. So, 2<9<3 in C means (2 < 9) < 3. 2 < 9 is 1, so, the value of 2 < 9 < 3 is 1.
You can fix it with (2 < 9) && (9 < 3).

Precedence in C operators == and ( = )

I have to analyze what some code in C does, and I have a doubt about what happens in a certain line. The code is
#define PRINTX printf("%d\n", x)
void problem() {
int x = 2, y, z;
x *= 3 + 2; PRINTX;
x *= y = z = 4; PRINTX;
x = y == z; PRINTX;
x == (y = z); PRINTX; // This line is the problem
}
This code snippet prints the resulting numbers:
10
40
1
1 // This result **
the problem is that I'm still trying to figure out why does the last line prints out x = 1, when the operation is x == (y = z). I'm having trouble finding out what that 1 means and the precedence of the operations. Hope someone can help me! :)
Nothing in the last statement changes the value of x, so its value remains unchanged.
Parens were used to override precedence, forcing the = to be the operand of the ==.
An operator's operands must necessarily be evaluated before the operator itself, so we know the following:
y is evaluated at some point before the =.
z is evaluated at some point before the =.
x is evaluated at some point before the ==.
= is evaluated at some point before ==.
That's it. All of these are valid orders:
z y = x ==
y z = x ==
x y z = ==
etc.
But whenever x, y and z are evaluated, we can count on the following happening:
= assigns the value of z (currently 4) to y and returns it.
== compares the value of x (currently 1) with the value returned by = (4). Since they're different, == returns 0 (which isn't used by anything).
As you see, nothing changed x, so it still has the value it previously had (1).
In the last statement, nothing is changing the value of x. We are testing if x equals something, but we aren't changing it's value.
So it continues having the same value as it had in the previous statement, in particular, a value of 1.
the reason is because the == operator checks if the 2 numbers are equal, and returns 1 if equal and 0 if not equal that is why it returns one you can check by making x= 1 and y=2 and using the == operator between them
The comparison result of x and assignment of y with (y = z) is discarded. Last line could have dropped the compare: y = z; PRINTX;.
The assignment is not subsequently used either, so the line could have been PRINTX;.

Associativity and Sequence Points in C

Since the associativity of '?' is from right to left,any 2 consecutive '?' operators must be treated as such,Right?
Now,
int x=-1;
int y=x?x++?x:-1:1;
I expect this to be executed as:
int y = x ? (x++?x:-1) : 1;
Now since its being executed from right to left,when encountering the first '?' in the statement,x's value is 0 and the expression is as
int y= x? 0 : 1;
hence i expected y to be 1,but it shows Zero on my dev-cpp.Where am i wrong?
You have the order of evaluation wrong. In a ? b : c, a is always evaluated first, then either b or c is evaluated.
I've marked up your example so that I can identify subexpressions:
c
int y=x?x++?x:-1:1;
a bbbbbbbb
(a) is evaluated, yielding -1, so (b) is evaluated. There, x++ is evaluated, yielding -1 again, so (c) is evaluated. At this point, x is 0.
Or, with more verbose, clearer code, it's as if you said:
int x = -1;
int y;
if (x != 0)
{
int new_x = x + 1;
if (x != 0)
{
y = new_x;
}
else
{
y = -1;
}
}
else
{
y = 1;
}
Operations:
Assign y to value =
if(x): --> x = -1, so true as it is non-zero
{
if(x): --> x = -1 ,so true as x will increment later due to post increment
x= x +1; --> increment x, so x = 0 . This is the value assigned. So y = 0;
else:
-1
}
else:
{
1
}
Hope this helps!
The answer to your question is that in C/C++ int y = x ? (x++?x:-1) : 1; we will hit two sequence points at ?. Any update operations to variable with in a sequence point will be effective after that sequence is over. So lets look at our example in hand.
First sequence point is first ? from left.
x=-1; (Actual Value)
x=-1; (Value used in expression)
y=-1?(x++?x:-1):1;
Second sequence point is second ? from left. As mentioned above the update operations are effective after sequence so even though x++ is there the value used in this sequence is -1 and updated value will be used in following.
x=0; (Actual Value, bcoz of x++)
x=-1; (Value used in expression)
y=-1?x:-1;
Now it will be
x=0; (Actual Value)
x=0; (Value used in expression)
y=x;
y=0;
Hope this make sense now.

what is the meaning of == sign?

I am trying to figure out what == sign means in this program?
int main()
{
int x = 2, y = 6, z = 6;
x = y == z;
printf("%d", x);
}
The == operator tests for equality. For example:
if ( a == b )
dosomething();
And, in your example:
x = y == z;
x is true (1) if y is equal to z. If y is not equal to z, x is false (0).
A common mistake made by novice C programmers (and a typo made by some very experienced ones as well) is:
if ( a = b )
dosomething();
In this case, b is assigned to a then evaluated as a boolean expression. Sometimes a programmer will do this deliberately but it's bad form. Another programmer reading the code won't know if it was done intentionally (rarely) or inadvertently (much more likely). A better construct would be:
if ( (a = b) == 0 ) // or !=
dosomething();
Here, b is assigned to a, then the result is compared with 0. The intent is clear. (Interestingly, I've worked with C# programmers who have never written pure C and couldn't tell you what this does.)
It is "equals" operator.
In the above example, x is assigned the result of equality test (y == z) expression. So, if y is equal to z, x will be set to 1 (true), otherwise 0 (false). Because C (pre-C99) does not have a boolean type, the expression evaluates to an integer.
Equality. It returns 1 if the operands are equal, 0 otherwise.
== means "is euual to". This operator has higher precedece than = (equal to) operator. So the equation x = y == z; will try to assign result of y==z to variable x. which is 1 in this case.
int main()
{
int x = 2, y = 6, z = 6;
x = y == z;
printf("%d", x);
}
let`s start like this:
x = (6==6)
It asks is 6 equivalent to 6?: true
x = true, but since x is an int, x= 1
The new value of x is 1.
The following is printed:
1
It's saying
X will equal either true/1 or false/0.
another way to look at that line is this:
x = ( is y equal to true? then true/1 or false/0 )
== operator used for equality..
here in u r example
if y is equal to z then x will hav true value otherwise x will hav false
Think about it like this:
= means give something a value.
== means check if it is equal to a value.
For example
int val = 5; //val is 5
//= actually changes val to 3
val = 3;
//== Tests if val is 3 or not.
//note: it DOES NOT CHANGE the value of val.
val == 3;
int new_val = val == 3; //new_val will be 1, because the test is true
//the above statement is the same as
bool is_val_3 = false;
if( val == 3 )
is_val_3 = true;
int new_val;
new_val = is_val_3;
//putting it together,
val = new_val == 2; //sets val to 0. do you understand why now?

Resources