June 20th, 2013, 08:54 AM
Help on for loop condition
I was reading The complete reference and below is code for one of the programs there.
The above FOR loop exits when the entered value is 0. For better understanding I have printed it to check it the value of t is defaulted to 0 but below is the output
int sqrnum(int num);
printf("The value of t is %d \n",t); //This is added by me
for(prompt(); t=readnum(); prompt())
printf("Enter a number: ");
int sqrnum(int num)
The value of t is 692
Enter a number: 2
Enter a number: 692
Enter a number: 0
Could some one please help me in understanding how the loop exists when entered value is 0
June 20th, 2013, 09:22 AM
Zero is false, non-zero is true. When readnum returns zero and assigns it to t, that evaluates to zero which is false. False causes you to exit the for loop.
June 20th, 2013, 11:05 PM
for( expression1 ; expression2 ; expression3 ) statement...
expression1 is evaluated before the first iteration.
After each iteration, expression3 is evaluated.
Both expression1 and expression3 may be ommited.
If expression2 is ommited, it is assumed to be 1. statement is executed repeatedly until the value of expression2 is 0.
The test on expression2 occurs before each execution of statement.
0 == false --> exit
June 20th, 2013, 11:35 PM
Thank you for the reply
I wasn't aware that the test operator assigns the lvalue to the variable AND ALSO RETURNS THE LVALUE .
Was under the understanding that assignment operator on successful assignment (even with successful assignment if 0) returns true some what like unix flavour but now things look clear :)