Sample Video Frame

Created by Zed A. Shaw Updated 2024-11-15 13:50:32

Exercise 8: If, Else-If, Else

In C, there really isn't a Boolean type. Instead, any integer that's 0 is false or otherwise it's true. In the last exercise, the expression argc > 1 actually resulted in 1 or 0, not an explicit True or False like in Python. This is another example of C being closer to how a computer works, because to a computer, truth values are just integers.

However, C does have a typical if-statement that uses this numeric idea of true and false to do branching. It's fairly similar to what you would do in Python and Ruby, as you can see in this exercise:

View Source file ex8.c Only

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i = 0;

    if (argc == 1) {
        printf("You only have one argument. You suck.\n");
    } else if (argc > 1 && argc < 4) {
        printf("Here's your arguments:\n");

        for (i = 0; i < argc; i++) {
            printf("%s ", argv[i]);
        }
        printf("\n");
    } else {
        printf("You have too many arguments. You suck.\n");
    }

    return 0;
}

The format for the if-statement is this:

if(TEST) {
    CODE;
} else if(TEST) {
    CODE;
} else {
    CODE;
}

This is like most other languages except for some specific C differences:

Other than that, the code works the way it does in most other languages. You don't need to have either else if or else parts.

What You Should See

This one is pretty simple to run and try out:

View Source file ex8.sh-session Only

$ make ex8
cc -Wall -g    ex8.c   -o ex8
$ ./ex8
You only have one argument. You suck.
$ ./ex8 one
Here's your arguments:
./ex8 one 
$ ./ex8 one two
Here's your arguments:
./ex8 one two 
$ ./ex8 one two three
You have too many arguments. You suck.
$

How to Break It

This one isn't easy to break because it's so simple, but try messing up the tests in the if-statement:

Extra Credit

Previous Lesson Next Lesson

Register for Learn C the Hard Way

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.