Learn C Programming Language
The Go to Statement in C programming
Definition of Go to Statement
The go to statement is an unconditional branch. The result of the go to statement is a change in the flow of control to the first statement after the label specified in the goto statement.
A label is an identifier followed by a colon. A label must appear in the same function as the go to statement that refers to it.
Using go to statement in C programming language is considered as poor programming approach.
Go..To Statement Syntax
Forward Reference:
goto label;
---------------
---------------
---------------
label:
statement 1;
statement 2;
statement 3;
Backward Reference:
label:
statement 1;
statement 2;
statement 3;
---------------
---------------
---------------
goto label;
Go to Statement Example
The program below uses goto statements to loop ten times and print the counter value each time.
After initializing count to 1, the if condition tests count to determine whether it’s greater than 10 (the label start: is skipped because labels do not perform any action).
If so, control is transferred from the goto to the first statement after the label end.
// Using the goto statement
#include <stdio.h>
int main( void )
{
int count = 1; // initialize count
start: // label
if ( count > 10 ) {
goto end;
} // end if
printf( "%d ", count );
++count;
goto start; // goto start on line 9
end: // label
putchar( '\n' );
} // end main
Output:
1 2 3 4 5 6 7 8 9 10
Ads Right