It may seem strange to have multiple variable types when it seems like some variable types are redundant. But using the right variable size can be important for making your program efficient because some variables require more memory than others. For now, suffice it to say that the different variable types will almost all be used!

Before you can use a variable, you must tell the compiler about it by declaring it and telling the compiler about what its "type" is. To declare a variable you use the syntax <variable type> <name of variable>;. (The brackets here indicate that your replace the expression with text described within the brackets.) For instance, a basic variable declaration might look like this:

int myVariable;

Note once again the use of a semicolon at the end of the line. Even though we're not calling a function, a semicolon is still required at the end of the "expression". This code would create a variable called myVariable; now we are free to use myVariable later in the program.

It is permissible to declare multiple variables of the same type on the same line; each one should be separated by a comma. If you attempt to use an undefined variable, your program will not run, and you will receive an error message informing you that you have made a mistake.

Here are some variable declaration examples:

int x;

int a, b, c, d;

char letter;

float the_float;

While you can have multiple variables of the same type, you cannot have multiple variables with the same name. Moreover, you cannot have variables and functions with the same name.

A final restriction on variables is that variable declarations must come before other types of statements in the given "code block" (a code block is just a segment of code surrounded by { and }). So in C you must declare all of your variables before you do anything else:

Wrong

#include <stdio.h>

int main()

{

/* wrong! The variable declaration must appear first */

printf( "Declare x next" );

int x;

return 0;

}

Fixed

#include <stdio.h>

int main()

{

int x;

printf( "Declare x first" );

return 0;

}

Reading input

Using variables in C for input or output can be a bit of a hassle at first, but bear with it and it will make sense. We'll be using the scanf function to read in a value and then printf to read it back out. Let's look at the program and then pick apart exactly what's going on. You can even compile this and run it if it helps you follow along.

#include <stdio.h>

int main()

{

int this_is_a_number;

printf( "Please enter a number: " );

scanf( "%d", &this_is_a_number );

printf( "You entered %d", this_is_a_number );

You've reached the end of published parts.

⏰ Last updated: Jul 22, 2009 ⏰

Add this story to your Library to get notified about new parts!

C ProgrammingWhere stories live. Discover now