How while loop works

S

somenath

Hi All,

I have doubt regarding how compiler understands about while loop. For
example the bellow mentioned code produce the output as mentioned
bellow.

#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;
}
Value of i = 10
I/O:
I/O: Value of i = 9
I/O:
I/O: Value of i = 8
I/O:
I/O: Value of i = 7
I/O:
I/O: Value of i = 6
I/O:
I/O: Value of i = 5
I/O:
I/O: Value of i = 4
I/O:
I/O: Value of i = 3
I/O:
I/O: Value of i = 2
I/O:
I/O: Value of i = 1

My understanding of the behavior is when the execution encounter goto
statement it jumps to label: and when it find that it is inside while
loop it goes back to while(--i > 0) and execute the loop.
Is my understanding correct ?
If it is correct then my question is how "c" compiler understand that
it is inside loop?

Please help .

Regards,
Somenath
 
S

Stephen Sprunk

somenath said:
I have doubt regarding how compiler understands about while
loop. For example the bellow mentioned code produce the
output as mentioned bellow.

#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;
}
....
My understanding of the behavior is when the execution
encounter goto statement it jumps to label: and when it find
that it is inside while loop it goes back to while(--i > 0) and
execute the loop. Is my understanding correct ?

No, because if that were the case the first value printed would be 9 instead
of 10.

Basically, what is happening is that the compiler converts a while loop into
some gotos and if statements. For instance:

while (test) {
/* do something */
}

is translated as:

loop_start:
if (test)
goto loop_exit;
/* do something */
goto loop_start;
loop_exit:

This translates much more easily to how CPUs actually work. And, once you
understand that, you can see that your program is being translated into:

#include<stdio.h>
int main(void)
{
int i =10;
goto label;
loop_start:
if (--i > 0)
goto loop_exit;
label:
printf("\n Value of i = %d \n",i);
goto loop_start;
loop_exit:
return 0;
}
If it is correct then my question is how "c" compiler understand that
it is inside loop?

In this case, the compiler doesn't even need to know whether it's in a loop
or not, and "loops" may not even exist as you think of them once the code
hits the optimizer.

S
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top