Translate

Labels

Sunday 27 October 2013

C PUZZLES

Assignment Operators

What dopes the following program print?
#define PRINTX printf("%d\n",x)

main()
{
int x=2,y,z;
x*=3+2;
PRINTX;
x*=y=z=4;
PRINTX;
x=y==z;
PRINTX;
x==(y=z);
PRINTX;
}


Explanation



About define:
This program begins with the line

#define PRINTX printf("%d\n",x)

Any line in a C program that begins with the character # is a statement to the C Preprocessor. One job done by the preprocessor  is the substitution  of one token string by another. The define statement in the is program tells the preprocessor to replace all instances of the token PRINTX with the string printf("%d\n",x).

initially x=2
x *= 3+2                                               Follow the precedence table.

x *=(3+2)                                             As we saw earlier ,the assignment operators have precedence below the arithmetic operators.(*= is an assignment operator) . 

(x*=(3+2))

(x*=5)                                                  Evaluating.

(x=x*5)                                                Expanding the assignment to its equivalent form.

(x=10)

10

initially x=10
x*=y=z=4

x *=y=(x=4)                                        In this expression all the operator are assignment,hence associativity  determines the order of binding. Assignment operator associate from right to left.


x *=(y=(z=4))

(x*=(y=(z=4)))

(x*(y=4))                                           Evaluating.

(x*=4)

40


initially y=4,z=4
x=y==z

x=(y==z)                                         Often a source of confusion for programmers new to C is the distinction between =(assignment) and ==(test for equality).From the precedence table it can be seen that == is bound before =.

(x=(y==z))

(x=(TRUE))

(x=1)                                              Relation and equality operator yields a result of TRUE,an integer 1 or FALSE,an integer 0.


initially x=1,z=4
x==(y=z)

(x==(y=z))                                   In this expression the assignment has been forced  to have higher precedence that the test for equality through the use of parentheses.

(x==4)                                         Evaluating.

FALSE,or 0                                The value of the expression is 0.Note however that the value  has not changed (==does not change its operands ),so PRINTX prints 1.

No comments: