The statement most commonly used in
conditional branching in
computer science. Your bog-standard if statement looks something like this (examples are in
C, but will be syntactically similar to if statements in many languages) -
if ( condition ) { expression1; ...; }
Let's analyse this a little more. The condition can be evaluated into one of two values - true or false. Hence, the two simplest if statements are like this -
if ( true ) { printf("This will *always* be true.\n"); }
if ( false ) { printf("This will *always be false.\n"); }
In the case of the second example, your compiler will most likely flag this with a warning or error, saying the expression will never be executed. The above two examples obviously aren't any use, and don't show us anything about why conditional branching is so useful.
The reason conditional branching is so useful is because it allows us to make run-time decisions that could not be made at compile-time. For instance, we may ask a user to input a value, then we'd want to take action based on this value. We could use a construct similar to this -
if ( value < 0 ) printf("Please input a value larger than or equal to 0.\n" );
So, to analyse this statement:
If value is smaller than zero, then the conditional of the if evaluates to true, and therefore the expression is executed. In any other case (if the value is equal to or greater than zero), the conditional evaluates to false, and the expression is not executed.
You can see that being able to execute different instructions based on the values of data opens up many more possibilities than linear programs which do the same thing every time they're run!
Other if-based constructs are the if/else construct and the if/elseif construct, which look like this -
If/else construct-
if ( value > 0 ) {
printf("The value is larger than zero.\n");
} else {
printf("The value is not larger than zero.\n");
}
If/elseif construct-
if ( value == 2 ) {
printf("Value is equal to 2.\n");
} else if ( value == 3 ) {
printf("Value is equal to 3.\n");
}