Introduction to Variables

Share This Post

In this article, we will talk about variables in C programming. Variables are used to store values. They are names that point to some memory location. Variables has to be declared before use. Declaring mean announcing the properties of the variables. Properties include size and name of the variable. There is also definition of variable which mean allocating memory to a variable. Most of the time declaration and definition will be done at the same time. But this is not usually the case. It depends on the modifiers mentioned for the variable. We will talk more about this later. Let’s look at an example of how to declare a variable. The code below shows the declaration of variable named var of integer data type. Data type determines how much space a variable is going to occupy in memory.

int var;

By writing int var we are declaring a variable and requesting the compiler to allocate memory for the variable. Note that there is semi-colon after the variable declaration. This is how compiler separates one statement from another. Memory location depends on the data types. In our variable declaration above, we specified that var is of integer data type. This may take either 2 or 4 bytes memory depending on the system. You can also assign values to your variables at the time of declaration. This is called initialization. An example code that initializes a variable at declaration is shown below:

int var = 3;

Variable value can be changed after initialization as illustrated in the code below

Note that when changing the variable, we do not define the variable again. This is because memory is already allocated to the variable in the first definition and we cannot declare multiple variables with the same name.

C follows naming convention. Names of variables can be composed of letters or combination of letters and digits. The following are some of the rules foe naming variables

  1. Don’t start variable with a digit
  2. Beginning with underscore is valid but not recommended
  3. C language is case sensitive
  4. Special characters (@, #, %, ^, &, *..) are not allowed in the name of variable
  5. Blanks or white spaces are not allowed
  6. Don’t use Keywords to name your variables. words such as if, else, for, while, switch, int, float, long, double etc are reserved words and cannot be used in naming variables.

More To Explore