C conditional

Introduction to C conditional statements: if / else and switch

Any programming language can provide programmers with the ability to perform choices.

In some cases, we want to do X, in other cases, we want to do Y.

We need to check the data and make a selection based on the state of the data.

C provides us with two methods.

first of allifStatement, andelseAssistant, the second one isswitchstatement.

if

inifStatement, you can check that the condition is true, and then execute the code block provided in the braces:

int a = 1;

if (a == 1) { /* do something */ }

You can attach aelseIf the original condition is false, execute another block;

int a = 1;

if (a == 2) { /* do something / } else { / do something else */ }

Beware of a common source of errors-always use comparison operators==In comparison, not assignment operator=,otherwiseifUnless the parameter is0, For example, if you do:

int a = 0;

if (a = 0) { /* never invoked */ }

Why is this happening? Because the condition check will look for a boolean result (the result of the comparison), and0The number is always equal to the error value. Everything else is correct, including negative numbers.

You can have multipleelseBy stacking multiple blocksifstatement:

int a = 1;

if (a == 2) { /* do something / } else if (a == 1) { / do something else / } else { / do something else again */ }

switch

If you need to execute too many if/else/if blocks to perform the check, maybe because you need to check the exact value of the variable, thenswitchVery useful for you.

You can provide a variable as a condition, and a series ofcaseThe entry point for each value you expect:

int a = 1;

switch (a) { case 0: /* do something / break; case 1: / do something else / break; case 2: / do something else */ break; }

We need abreakUse keywords in each case to avoid executing the next case at the end of the previous case. This "cascading" effect can be useful in some creative ways.

You can add an "all-encompassing" label at the end, marked asdefault:

int a = 1;

switch (a) { case 0: /* do something / break; case 1: / do something else / break; case 2: / do something else / break; default: / handle all the other cases */ break; }

Download mine for freeC manual


More clang tutorials: