somenath said:
Hi All,
I have doubt regarding how compiler understands about while loop.
More idiomatically: "I have a question about while loops."
#include<stdio.h>
int main(void)
{
int i =10 ;
goto label;
while(--i 0)
{
label:
printf("\n Value of i = %d \n",i);
}
return 0;
}
Firstly, I would just like to point out that it's rarely a good idea to
use goto (in fact, I've never come across a good reason to use it in
"real" code).
But here, your reason for using it is to help to deepen your
understanding of C, and that's a pretty good reason, so let's look at
this very closely.
To do so, I am going to cheat. I'm going to invent an assembly language
that targets a non-existent machine, and then I'm going to pretend that
your C compiler converts your program into an assembly language program
for that machine.
Here are the relevant parts of the assembly language:
Rn - refers to register n
SET Rn, value - assigns value to register n
JMP address - jumps to given address
DEC Rn - reduce register n's value by 1
CMP Rn - compares value in register n with 0
JLE address - if last value compared was negative, jump to given address
PRINT Rn - prints newline, space, "Value of i = ", value of given
register, space, newline (!)
EXIT n - halts program with return code of n
Addresses start at A and continue in counting fashion.
Here, then, is your program after compilation:
ADDRESS INSTRUCTION
A SET R0, 10
B JMP F
C DEC R0
D CMP R0
E JLE H
F PRINT R0
G JMP C
H EXIT 0
If you follow through the logic here, you'll perhaps see why you're
getting the output that you see in your own code.
There's nothing magic about the while loop. It is very likely to be
translated as a simple compare and conditional jump at the top, with an
unconditional jump at the bottom (as in the above example). So this is
just a matter of what jumps where and when.
--
Richard Heathfield <http://www.cpax.org.uk>
Email: -www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999