Introduction To Programming

Why programs ? Programming is nothing but making the computers think the same way a human thinks. Programs are made for obtaining a specific solution which can even be solved by humans which when solved by us may consume time..

Wednesday, March 24, 2010

70

#define les(a,b)     a<b?a:b
int main()
{
int i=1,j=3,k;
k=les(i++,++j);
printf("%d %d %d",i,j,k);
return 0;
}

Output:
3  4   2


Logic:
While compilation happens ,macro identifier is replaced with associated character sequence.
i.e.,
les(i++,++j) is replaced by i++<++j?i++:++j
so now

k=i++<++j?i++:++j;
1 4 2


In this statement 1<4,so i++ is assigned to k(statement is true so 1st variable is returned i.e,i++).
k=i++;
2

so k=2 and 'i' is increment later(post increment) .so 'i' will became 3.

69

int main()
{
int i=0,j;
j=(i++,++i);
printf("%d %d ",i,j);
return 0;
}

Output
 2  2 

Logic:
As per the Associativity of the brackets ,j=++i(brackets associativity is left to right).The statements is equal to i++,j=++i;

These statements will executed like this:

line 1:     i++,         //'i' is equal to 1.
line 2:     j=++i;         //j=++i(preincrement) so j=2 and i=2



','(comma)operator is used to group one or more statements.

68

int main()
{
int i=0,j=0;
int k=2;
(i,j)=k;
printf("%d %d %d", i,j,k);
return 0;
}


Output:
0     2     2
Note:
gcc compiler will show one warning.
Logic:
We know that associativity of brackets always be left to right(i.e <-- in this direction). so j=k is assigned . The statement is equal to i,j=k;

67

int main()
{
int i,j;
i=3<3+2;
j=4<<1+1;
printf("%d %d ",i,j);

return 0;
}





Output

1     16

Logic:
In c program arithmetic operators (/,*,+,-) has higher precence than the conditional operators( < , > ,< =, > =,!=,==) and shifting operators( << , >> ). so addition operation is performed first.
i=3<5 results truth value 1.
j=4<<2 results 16.(read shifting post to know about the shifting operator).

66

int main()
{
printf("%d ",5>6==0);
printf("%d",5>6>0);
return 0;
}

Output:

1
0

Logic:

I think no need to explain about the operators > and == .

In 1st printf function:
5>6 gives false truth value(0).
0==0 gives true truth value(1).
so it'll print 1 in buffer.
in 2nd printf function:
5>6 gives false truth value (0)
0>0 gives false truth value(0)
so it'll print 0 in buffer.