C Programming Tutorial 46 – If Statement 

Did you read the last blog? Go read intro to logic! Are you new here? Start at the beginning, Intro to C!

The if statement is the most foundational flow control statements in programming. You are literally going to come across the if statement in probably every program you see or write. Make sure you watch the previous video as it is foundational to this one.

The if statement is foundational to branching. Branching is when your program only does something based on the truth value of some statement. The if statement can sometimes be called a conditional statement.

The general structure for an if statement is:

Please memorize this format. If you remember me explaining an expression in previous videos, you will know that an expression is anything that is evaluated to a value. In this situation, the expression will always evaluate to one of two values…true, or false.

The way the if statement works is first the expression will evaluate to true or false. If it is evaluated as true, whatever is inside the section below will be executed. This brings up some important points. I haven’t spent much time to express the name of certain characters, but it is important that you know the name of what characters are called. I know it seems stupid, but so many people call characters the wrong thing and it introduces confusion.

( left parenthesis 

) right parenthesis 

{ left curly brace 

} right curly brace 

/ two forward slashes 

When you have an left and right curly braces, you are creating what is known as a code block. This is an important term that will come up when we start talking about variable scope, but we will discuss that later. Some people may also call this the body of the if statement.

Now, as for the expression that goes inside of the parentheses, how does it get evaluated to true or false? Well, let’s start with the easiest example. Let’s say we had a bool variable called calebIsfat.

Any bool variable inside of an if statement is super easy because it stores a value of either true or false. To test this value, all you have to do is put the variable name:

where exercise is some function we could create on our own.    

To help you think through what this would look like if the value was true, write this:

It is easy to see that the code block will be ran.

In this situation it is clear that the code block will not be ran. 

You can see that when it comes to bool variables, it is super easy to figure out whether or not the body of the if statement will be ran or not, but what happens when you have values other than true or false? We will be discussing that in the upcoming blogs.

Ready to learn more? Read the next blog on How to Write If Statement with Boolean Variables!

Leave a Reply

Your email address will not be published. Required fields are marked *