C control flow and goto scope rules:
Point out the error in this program that jumps to a label inside another function.
#include
int main()
{
void fun();
int i = 1;
while (i <= 5)
{
printf("%d
", i);
if (i > 2)
goto here;
i++;
}
return 0;
}
void fun()
{
here:
printf("It works");
}
-
ANo Error: prints "It works"
-
BError: fun() cannot be accessed
-
CError: goto cannot takeover control to other function
-
DNo error
-
ENone of the above
Answer
Correct Answer: Error: goto cannot takeover control to other function
Explanation
Introduction / Context:This problem validates understanding of goto scope rules. A goto can only jump to a label that is in the same function and within the same translation unit in scope. Crossing function boundaries with a goto is prohibited by the C standard.
Given Data / Assumptions:
- A label
here:is defined insidefun(). main()attemptsgoto here;.- Loop and print statements otherwise are ordinary.
Concept / Approach:Labels in C have function scope. They are not global symbols; they are only visible and valid within the function in which they are defined. Therefore, goto here; inside main() cannot legally reference here: defined in fun(). Compilers will emit an error such as “label ‘here’ used but not defined” in main, or “label exists in a different function.”
Step-by-Step Solution:Identify the label definition site: in fun().Identify the jump site: in main().Apply rule: labels have function scope → cross-function jump is invalid.Fix by moving the label into main() or restructuring code using functions/returns.
Verification / Alternative check:Compiling yields an error. Refactor to if (i > 2) { fun(); break; } to achieve a similar effect legally.
Why Other Options Are Wrong:fun() cannot be accessed — access is fine; the problem is the cross-function goto. No error — incorrect.
Common Pitfalls:Misunderstanding label scope; using goto for inter-function control transfer instead of calls/returns or flags.
Final Answer:Error: goto cannot takeover control to other function