005 # puzzles on c
By dholey
@dholey (1383)
India
6 responses
@tmaheshwari (170)
• India
24 Jan 07
First of all, this program will not compile...
WHY? Let me explain...
See the statement: x = 10 && y = 6
The precedence of ‘&&’ is more than assignment… so it would become like “x = (10 && y) = 6”
Now, “10 && y” is actually a constant.. so it would become like “x = (const number) = 6;
Here… “const number = 6” is an error known as ‘L-value’ error. I hope this is clear now…
Again, let me try to correct you, may be u want to write your program in this way:-
void main()
{
int x=10,y=5,z;
z= (x=10 && (y=6))?100:200;
printf("\n z=%d ",z);
}
Now .. It will compile and result would come ‘z = 100’ because x = 10 is a true condition and y=6 is a assignment of 6 in y which becomes true.
So … z = true ? 100 : 200,,,, very clear that the value of z would become 100 here.
1 person likes this
@swaroop_sv2003 (531)
• India
24 Jan 07
Ohh I didn't know that this program had a twist like this. Good going.
@senthilp_1985 (30)
• India
28 Jan 07
Hi dholey,
output is simple. tell me whether i am right.
output:
z=100
Reason:
1. As x=10 so x=10 condition is true.
2. y=6 is a nonzero value even it is true.
3. So condition of ternary operator is true. Hence 100 is returned and assigned to z
4. finally we get x=10 and y=6 and z=100
1 person likes this
@_Greeneye_ (1526)
• India
29 Jan 07
hi dholey me back aftr a long time u nd tmahes.... doin extremely well. i dont know much abt programming but these discussions doing a great job for beginners
@kingadnan (1538)
• Pakistan
23 Jan 07
sorry dholey i am not a student of C language i don't know its output please tell me its out put .. can you teach me C language? send me private message
@swaroop_sv2003 (531)
• India
24 Jan 07
If the program is executed as given above it will lead to an error since it is y=6 and it should be y==6. So the correct program should be
int main()
{
int x=10,y=5,z;
z= (x=10 && y==6)?100:200; // changed y=6 to y==6
printf("\n z=%d ",z);
return 0;
}
The above program would output z=200 since the condition y==6 is false so 200 would be stored to z.