Discussing the use of break in C

Image by pramit marattha from Pixabay

On the C programming subreddit there’s a discussion where a student has been old he should never use break in C. As one comment says, “The teacher is a nitwit” and I agree with that comment.

I use break (a) to exit loops early and (b) to exit every branch of a switch statement unless I want it to drop through or else that case does a return. I use switch a few times in the asteroids source code and there’s examples of all three instances of using breaks, using returns and dropping through cases (no break).

Here’s an example of the latter. It controls the logic of what to display when you start or restart a level after losing lose a life. If you have one life left it prints “Last life” otherwise it prints how many you’ve got. Actually I think it’s a bit of an overkill and an if else would have done just as well


	switch (Player.lives) {
		case 1:sprintf_s(buffer, sizeof(buffer), "Last Life!");
		case 2:
		case 3:sprintf_s(buffer, sizeof(buffer), "Lives left: %d", Player.lives);

So probably not the best example of using a switch! But it illustrates a point.