Jump statements in c
In c, jump statements allows to transfer or jump execution control of program statements to another statements in that program.
c language provides three type of jump statement.
- break
- continue
- goto
break
It is mostly used to exit loop or switch.
In loops, it is used with if else condition, when any specific condition satisfies, it breaks the loop cycle and comes out of the loop.
In switch, every case ends with break keyword, if any case is matched with switch expression, break transfer the control out of switch statement.
break with for loop
void main()
{
for(int i = 0; i < 7; i++)
{
if(i == 5){
break;
}
}
}
continue
continue is also a jump control statement, used in loops. It is used with if condition inside loops to skips or jumps the current iteration or loop cycle.
#include<stdio.h>
void main()
{
for(int i = 0; i < 10; i++)
{
if(i == 5){
continue;
}
printf("%d ", i);
}
}
Explanation
When value of i becomes 5, if condition inside loops become true and continue will skip the current loop cycle.
goto
goto allows to transfer program execution control from given label to specified label.
Syntax
goto label;
.
.
label: statement;
Example
#include<stdio.h>
void main()
{
int i = 10;
goto hello;
i = i + 20;
hello:
printf("%d ", i);
}
goto should be used very carefully in c program, because it makes code unreadable, and difficult to find errors.