Home » Syntax References

Syntax of break statement in C/C++ programming language

C/C++ programming language break statement: what is break, when it is used and how, where t is used? Learn about break statement with Syntax, Example.

break is a keyword in C, C++ programming language and it is used with two statements:

  1. Looping statements (for, while and do while) - break is used to break (terminate) the execution of loop body and transfers the program’s control to the next statement written after the loop body.
  2. Switch case statement - break is used to transfer the program’s control from switch statement body to the next statement written after the switch.

Here, is the syntax of break statement with loop statement in C/C++ programming:

for (counter_initialization; test_condition; counter_increment)
{
	//statement(s)
	if(test_condition)
		break;
	//statement(s)
}
//outer statement(s)

If the test_condition written within the loop body is true (non zero) value, execution of loop will be stopped and program’s control will move to outer statement(s).

Here is an example: We will run loop from 1 to 10 and as value of loop counter reached to 7 break will be executed.

Consider the given example:

#include <stdio.h>

int main()
{
	int loop; //loop counter 
	
	for(loop =1; loop<=10; loop++)
	{
		if(loop==7)
		{
			printf("break...\n");
			break;
		}
		printf("%d\n",loop);
	}
	
	printf("BYE BYE!!!\n");
	
	return 0;
}

Output

1 
2 
3 
4 
5 
6 
break...
BYE BYE!!!

Syntax of continue statement in C/C++ programming language:

switch (variable)
{
	case case_value1:
		block1;
		[break];
	case case_value2:
		block2;
		[break];
	.
	.
	.
	default:
		block_default;
}

Program will check the value of variable with the given case values, and jumps to the particular case block if case value matched.

For example: if the value of variable matches with the case_value2, it will execute the statement(s) written in block2.

break is optional here, we must use if we want to break the execution of switch statement, if break is not found after the block (statements written in that particular block), it will execute the statement of next case.

If any of the case values does not match with the variable, default block will be executed.

Consider the given example:

#include <stdio.h>

int main()
{
	int a=2;
	
	switch(a)
	{
		case 1:
			printf("One\n");
			break;

		case 2:
			printf("Two\n");
			break;			
		
		case 3:
			printf("Three\n");
			break;		

		default:
			printf("Default\n");
	}
	return 0;
}

Output

Two



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.