A variable is a named data storage location in your computer’s memory. By using a variable’s name in your program, you are in effect, referring to the data stored there.
For many compilers, a c variable name can be up to 31 characters long. (It can actually be longer than that, but the compiler looks at only the first 31 characters of the name.)
In C, variable names must declared as follows:
- The name can contain letters, digits, and the underscore character(_).
- The first character of the name must be a letter. The underscore is also a legal first character, but its use is not recommended.
- Case matters (that is upper and lowercase letters). Thus, the names count and count refer to two different variables.
- C keywords can’t be used as variable names. A keyword is a word that is part of the C language.
The following list contains some examples of valid and invalid C variable names;
Variable Name | Valid |
Age | Valid |
Hello2x5_abc | Valid |
Hello_world | Valid |
_1994_born | Valid but not recommended |
Hello#world | Invalid: contains the illegal character # |
Int | Invalid: Int is a C Keyword |
32gamer | Invalid: digit or number is not recommended |
Because C is case-sensitive, the names age, AGE, and Age would be considered three different variables.
C programmers commonly use only lowercase letters in variable names, although this isn’t required. Using all-uppercase letter is usually reserved for the names of constants.
Declaring Variables
Before you can use a variable in a C program, it must be declared. A variable declaration tells the compiler the name and type of a variable and optionally initializes the variable to a specific value.
If your program attempts to use a variable that hasn’t been declared, the compiler generates an error message.
A variable declaration has the following form,
- data_type_name variable_name;
Data_type_name specifies the variable type and must be one of the keyword listed. Variable_name is the variable name, which must follow the rules mentioned earlier.
You can declare multiple variables of the same type on one line by separating the variable name with commas.
- int rollno,grade, age /* there integer variables */
- float percent, total /* two float variables */
C – Code
int i, j, k;
float pi, xcords, ycords;
double d;
char c, ch;
C – Code
int x=20, y=20, c;
float a=3.5, b=2.5;