C wars: Chapter Three: Revenge of the if
CodeLongAndPros (1589)

Chapter three: Revenge of the if

Today I will be talking about booleans and if, else if, else constructs.

First, before we get to the if, I'd like you to meet a new data type:

The boolean!

This is a type that has two possible values: 1 or 0.


  • true
  • false

To talk to your friend the bool, you have to #include another file: stdbool.h

Can you guess what this is for?

It is the Standard boolean header

You can use the true and false keywords to set the value of a bool:


bool key_pressed = true;
bool uses_windows = false;

But what use is that?

Let me introduce you to bool's partner, the comparision operators.

There are 9:

  • ==: equals
  • !=: not-equals
  • >: greater-than
  • <: less-than
  • <= : less-than-or-equals
  • >=: greater-than-or-equals

"But wait", you say, "You can't count! That's 6!"

Well, yes, but actually no.

There are three more:

  • !: not.

This one makes true be false, and false be true.

So to toggle boola, you can do boola = !boola.

  • &&: and.

This one is true if boola and boolb are both true:

boola && boolb

  • ||: or.

This one is true if boola or boolb is true

Note: you can't compare char* with ==

The if

Now, it's time for the big reveal.

How do I control my programs?

You use the if construct.

The syntax for if is:

if (boolean) {

The code in between {} will run if boolean is true.


if (1==1) {

You can use the else if to run code if bool1 is false, but bool2 is true:

if (bool1) {
} else if (bool2) {

And finally, you can use else to run if any of the other if's are false:

if (bool1) {
} else if (bool2) {
} else {
    spam && eggs;

There is one more syntax for an if statment.

This one only works on one statment:

if (a)
else if (b)
    spam && eggs;

One more thing:

You need to learn how to compare strings.

You use strcmp(a, b) to do so.

strcmp is in string.h.

To compare char a and char b:


char* a = "Hello";
char* b = "Hello";

bool a_is_b = !strcmp(a, b);

Note that if a == b, strcmp returns 0, hence the use of not.

Your homework:

Make a program that asks the user for their name.

If their name is Steve jobs, print You own apple.
If their name is Bill gates, print You own MS..
If their name is Richard stallman, print You founded GNU.
Otherwise, print I don't know you.

So long!

Part One: The Segfault menace

Part Two: The data wars

Part Three: Revenge of the if

Part Four: A new loop

Part Five: The Empire points back

Part Six: Return of the function

You are viewing a single comment. View All
CodeLongAndPros (1589)

@DynamicSquid Super secure test.

Can't go into much detail, but there was an audio copy.

They had to scan a qr to get to it.
Opened in google drive and made a copy.

Thing is, people didn't sign out of the iPads.

My friend had a copy.

Had to sign out of all the iPads.