In the last blog I spoke of how if statements work. In this blog we are going to write a very simple if statement with a bool variable! Remember that we have to have #include <stdbool.h> in our code. Are you new here? Start at the beginning, Intro to C!
This works and all and you can see that it adds a layer of functionality to our program, but this really isn’t that cool. You can see that we are selves are assigning true to the bool variable, so we wouldn’t really even need this conditional. We know it’s going to run, so we could just print what we want to print and delete the conditional.
You have to realize when we release our software, we are not going to be able to change the source code all of the time. If I put true in the code like this, imagine it being etched in stone. So why even use if statements if we know they are going to run?
The beauty of these conditionals is if we do not know the value of something ahead of time. To see this clearly, why don’t we write a program that asks the user if they think pizza is healthy and if they say yes, Give them access to the app. Now, one way to take a bool value from the console is to take a number and convert that to bool.
If they put 1, they get approval, if they put 0, nothing happens.
Let’s try it!
You can see that it works as expected, but what happens if we put something like 20?
Well, if you remember, bool variables store there data as either 0 or 1. Anything not 0 is stored as 1.
A similar principal is applied when it comes to if statements. What if we do not have a simple true or false variable in the if statement expression, but rather a number:
If it is easier to think about, visualize it like this:
This is not as clear because the value is not already true or false. We as software developers have to learn what the programming language interprets as true or false. In C, every non zero number is considered to be true. So the code block will be executed.
Now, we understand how to evaluate simple expressions, but what if we wanted to do something like create an application that allows people to enter a number and we want to check if that number is above or below a certain value?
These are a bit more complex because they require a special kind of operator knows as a relational operator, or what some people call a comparison operator. That is what we will be discussing in the next video, see you then!
Ready to learn more? Read the next blog on good coding practices!