I added an if and switch tutorial

Teachjer and blackboard
Image by mohamed Hassan from Pixabay

The next tutorial is Simple control flow in C. This demonstrates how to do if, if else and then switch statements. These are pretty siomple concepts but they are fundamentals so you do need to know them.

One thing I didin’t show in the switch tutorial is that you can mix in labels for that real write-only code experience. It’s not a technique I recvommend which is why its NOT in the tutorial but if you promise never to use this except in the rarest of circumstances, here’s what I mean.

#include <stdio.h>

int main() {
	int a = 10;
	switch (a) {
	case 1:
	case 2:
	case 3:
	case 4:
	{
		printf("a<5\n");
		break;
	};
	case 5:
fred:
	case 6:
		printf("a ==5 or a ==6\n");
		break;
	case 7:
	case 8:
	case 9:
		printf("a <9\n");
	case 10:
	{
		printf("a=10\n");
		goto fred;
	}
	default:
		printf("a not in range 1-10\n");
		break;
	}
}

The label is the line fred: and you can see in case 10 that after printing “a=10\n”, it jumps to fred which is just after the 5 case. That does nothing and falls through to the 6 case where it prints out “a ==5 or a ==6\n”. It’s not recommended but at least now if you ever see a jump to a label in a switch statement you can be sure that the programmer was not really at the top of his or her game.

(Visited 2 times, 1 visits today)