C Programming - Control Instructions - Discussion

8. 

Point out the error, if any in the while loop.

#include<stdio.h>
int main()
{
    void fun();
    int i = 1;
    while(i <= 5)
    {
        printf("%d\n", i);
        if(i>2)
            goto here;
    }
return 0;
}
void fun()
{
    here:
    printf("It works");
}

[A]. No Error: prints "It works"
[B]. Error: fun() cannot be accessed
[C]. Error: goto cannot takeover control to other function
[D]. No error

Answer: Option C

Explanation:

A label is used as the target of a goto statement, and that label must be within the same function as the goto statement.

Syntax: goto <identifier> ;
Control is unconditionally transferred to the location of a local label specified by <identifier>.
Example:


#include <stdio.h>
int main()
{
    int i=1;
    while(i>0)
    {
        printf("%d", i++);
        if(i==5)
          goto mylabel;
    }
    mylabel:
    return 0;
}
 

Output: 1,2,3,4


Shiwam said: (Sep 11, 2011)  
Is it does not give prototype error? Why?

Yogesh Yadav said: (Mar 14, 2012)  
In this while there is no way to increment the value of I so that I can reach to more than 2 and then reach the goto statement. So before reaching the goto statement, the program is going to end.

Sv (Savitru) said: (Jul 6, 2013)  
Can we declare a new function inside the main function and define it outside main? Is it possible? Someone explain me details.

Poorani said: (Mar 3, 2015)  
Actually why it is an error?

Since label (here) is in another function it is not working ah? I didn't get it?

Khush said: (Aug 4, 2015)  
#include <stdio.h>
int main()
{
int i=1;
while(i>0)
{
printf("%d", i++);
if(i==5)
goto mylabel;
}
mylabel:
return 0;
}

In this example is there will any change in output will done if i==5. As there is no printf statement with it.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.