4 Expression-operator 2
4 Expression-operator 2
Equals == x == y NOT x = y
Greater than > x > y
Less than < x< y
Greater/equals >= x >= y
Less than/equals <= x <= y
Not equal != x != y
#include <stdio.h>
int main ()
{
int w=10,x=20,y=30,z=40;
int temp1, temp2;
temp1 = x * x /++y + z / y;
printf ("temp1= %d;\nw= %d;\nx= %d;\ny= %d;\nz= %d\n",
temp1, w,x,y,z);
y=30;
temp2 = x * x /y++ + z / y;
printf ("temp2= %d;\nw= %d;\nx= %d;\ny= %d;\nz= %d\n",
temp2, w,x,y,z);
return 0;
}
Conditional Operator
The conditional operator essentially allows you to embed an “if”
statement into an expression
Generic Form
exp1 ? exp2 : exp3 if exp1 is true (non-zero)
value is exp2
(exp3 is not evaluated)
if exp1 is false (0),
value is exp3
(exp2 is not evaluated)
Example:
z = (x > y) ? x : y;
This is equivalent to:
if (x > y)
z = x;
else
z = y;
Comma Operator
An expression can be composed of multiple
subexpressions separated by commas.
– Subexpressions are evaluated left to right.
– The entire expression evaluates to the value of the
rightmost subexpression.
Example:
x = (a++, b++);
a is incremented
b is assigned to x
b is incremented
– Parenthesis are required because the comma operator has
a lower precedence than the assignment operator!
The comma operator is often used in for loops.
Comma Operator and For Loop
Example:
int i, sum;
for (i=0,sum=0;i<100;i++){
sum += i;
}
printf(“1+...+100 = %d”, sum);