icp/oer/courses/c-basics/sections/02-basic-language-features/03-conditionals/content.html

28 lines
1.7 KiB
HTML

<p>
Almost every program or algorithm needs some kind of <b>conditional branching</b>. It is used to control the flow of your program.
The most common form in any programming language is the if-statement or sometimes called if-then-else-statement.
It is used to define parts of your code, which are only executed, if certain conditions are met.
</p>
<p>
The if-statement consist of the keyword <b>if</b>, followed by an expression and then followed by a statement.
The statement can be a normal statement as seen before or more commonly a block statement, which is just a group of statements treated as one. They are opened and closed by curly braces.
If you want to define behavior, for when the condition is not met, you follow your if-statement up with an else-statement.
</p>
<p>
The if-statement works by evaluating the expression. If it is true, it will execute the following statement, if not, it will jump over
it to the next statement.
</p>
<p>
Because C has no boolean values by default, any non zero value will be interpreted as true and all zeros to false.
This can be useful. E.g if you want to check for null-pointers, you only have to put the pointer into the statement.
But it can be dangerous to. The compiler won't warn you, if you forget to use any boolean operators.
</p>
<p>
Normally you form your expression with boolean operators(<b>==</b>,<b>!=</b>,<b>&lt;</b>,<b>&gt;</b>,<b>&lt;=</b>,<b>&gt;=</b>)
and logical operators (<b>!</b>,<b>&&</b>,<b>&#124;&#124;</b>). But as mentioned before you don't have to use them.
Sometimes it is easier and shorter to use the fact that any non zero value is true.
</p>
<p>
Read trough the following examples and do the comparison task in the end of the file.
</p>