Variable in C language

variable in c language

Do you start learning C programming? If you’re reading about the “Variable in C language”, then it is likely that you answered Yes.

How many of you are looking for the answer to the below questions related to variables in C. If so, you are at the right place.

  • What is variable in C?
  • Does variable allow to modify the value at run time?
  • How to declare and use the variable in C language.
  • What is the variable used for?
  • What is the naming rule for the variable?

 

A variable is a very important element of the C language. In this blog post, you will learn what a variable is, why the variable is important, and how to use variables in C Programming. We will also see the naming rules of a variable in C.

 

What is variable in C?

In C programming, a variable is a storage location that contains some value known or unknown. Why I am saying known or unknown you will understand at the end of the article. A symbolic name (identifier) is associated with a variable and usually, we used this name to refer to the stored value. For example:

int data = 27;

Here, data is a variable of int type and it has integer value 27. Variable names are just the symbolic representation of a memory location.

The value of a variable can be changed at different times of execution and it may be chosen by the programmer in a meaningful way. For example,

//atic is integer type variable and assigned 6  
int atic = 6;

//Now changing value of atic 6 to 27
atic = 27;

 

Each variable in C has a specific data type, which determines the size (Generally in Byte) and layout of the variable’s memory. It also determines the range of values that can be stored within that memory and the set of operations that can be applied to the variable.

 

variable-copy

Note: In C language, each variable bind with two important properties, scope, and extent. Here I will not discuss the extent and scope. You can read the article “C storage class” for more information.

Variable Declaration Syntax:

A typical variable declaration is of the form:

Type Variable_Name;

If you want you can declare multiple variables at a time. See the below example,

For example,

Type Variable1_Name,Variable2_Name, Variable3_Name;

Type can be pre-defined(int, char, float) or user-defined(structure, union or enum etc.).

 

✍ Note: C variable name should be unique in a given scope otherwise you will get a compiler error.

 

How/Why use variables in C programming?

I believe this question comes to mind of each newbie. When I had started learning C programming then it also came to my mind. So let’s understand these questions.

We will understand these questions with a problem because the best way to understand any concept solve the problems related to the concept.

I have a question for you, my question is to write a C program that takes input from the user and displays it on the console“. For your information, I want to let you know that using the scanf() function, you can take input from the user and printf function print on the console.

Now you know the functions that take the input and print on the console. But still, one mystery is unsolved.

What this mystery is, the mystery is where you will store the input which you will get from the user. Now, what you thinking is. Yes, you are thinking in the right direction, a variable can solve your problem.

So what we have understood is that whenever in the program you need to store the information in the memory we use the variable. Now I believe you understand why the variable is required.

Let’s see an example, the following code taking an integer value from the user and displaying it on the console screen.

#include <stdio.h>

int main()
{
    //integer variable
    int data;

    //taking input from the user
    scanf("%d",&data);

    //printing the value on console
    printf("data = %d",data);

    return 0;
}

 

 

Variable declaration and definition:

Let’s understand that what is the meaning of declaration and definition in C programming with some example code.

Variable declaration:

Declaration introduces an identifier and describes its type ( type of variable, or function). It only provides sureness to the compiler at the compile time that identifier exists with the given type, so that compiler proceeds for further compilation without needing all detail of this variable. Basically, A declaration is what the compiler needs to accept references to that identifier.

When we declare a variable, then we only give the information of the variable to the compiler, but there is no memory reserve for it. It is only a reference, through which we only assure the compiler that this variable exists somewhere in the code.

These are the example of declarations:

extern int data;

extern int fun(int, int);

// extern can be omitted for function declarations
double foo(int, double);

 

Some practice questions for you:

Using the variable p write down some declarations:

✌ (Don’t see the answer do it first yourself)

1. An integer variable.
2. An array of five integers.
3. A pointer to an integer.
4. An array of ten pointers to integers.
5. A pointer to pointer to an integer.
6. A pointer to an array of three integers.
7. A pointer to a function that takes a pointer to a character as an argument and returns an integer.
8. An array of five pointers to functions that take an integer argument and return an integer.

Solution:

1. int p; // An integer
2. int p[5]; // An array of 5 integers
3. int*p; // A pointer to an integer
4. int*p[10]; // An array of 10 pointers to integers
5. int**p; // A pointer to a pointer to an integer
6. int(*p)[3]; // A pointer to an array of 3 integers
7. int(*p)(char *); // A pointer to a function a that takes an integer
8. int(*p[5])(int); // An array of 5 pointers to functions that take an integer argument and return an integer

 

Variable definition:

A definition is where the identifier is described. In another word, you can say where the identifier is instantiated/implemented. It is what the linker needs at the time of linking (Symbol Resolution and Relocation). There are three types of linkage in C, none, internal, and external.

These are definitions corresponding to the above declarations:

int data;

int fun(int a, int b)
{
    return (a+b);
}

double foo(int a, double b)
{
    return (a*b);
}

 

The C variables get the storage at the time of definition. Generally, definition and declaration occur at the same time and a definition can be used in the place of a declaration but vice versa is not applicable. Example of declaration and definition at the same time:

//definition and declaration of integer variable
int hight; 

//definition and declaration of character variable
char data; 

//declaration and definition of integer 
//variable with initialization.
int len = 0;

 

✍ Note: In C, An identifier can be declared as often as you want but can define only once.

 

When a declaration is required in C?

Variable declaration is useful when you are working on a project which contains multiple files. Sometimes you need to use the variable which has been defined in another file. In that scenario, you need to declare the variable in the file where you want to use it.

Let’s see an example to understand the importance of the identifier declaration. Suppose a project contains two files Display.c and Calculation.c. A variable global variablegData’ which has been defined in Calculation.c and need to access in Display .c. So you have to declare the ‘gData’ in Display.c using the extern keyword. If you will not declare it you will get the linker error.

Calculation.c:

//File:
//Calculation.c

#include <stdio.h>

int gData; //Global Variable

int main()
{
    int a,b;

    printf("Enter the data\n");

    scanf("%d%d",&a,&b);

    gData = a+b; //Add the value of a and

    return 0;
}

 

Display .c

//File:
//Display.c

//declaration
extern int gData; 

int display()
{
    printf("Addition of Data = %d",gData);
}

 

 

Naming Rule of the variable in C:

A variable name can be composed of letters, digits, or underscore. C is a case-sensitive language so upper and lower case are totally different from each other. Supposed you create a variable “DATA” (upper case) and “data” (lower case) are different.

Following are the rules to give a name to the variables in C:

A variable name can only have a sequence of digits, underscores, lowercase, uppercase Latin letters, and most Unicode characters.

Example,

int data;

int dat2a;

int _data;

int _Da2ta;

 

The first character of a variable name should be either a letter or an underscore. Example,

int 2data; //Invalid

float 9test; // Invalid

int abc; //Valid

int Abc; //Valid

 

Keywords can not use as an identifier in C programming. Example,

int switch;  //invalid

float for;   //invalid

int goto;   //invalid

 

✍ Note: You should always use a meaningful name for a variable. It increases the code readability.

 

Types of Variables in C:

At a high level, you can categorize the C variables into 3 types.

1. Local Variable:

A local variable is a variable that is declared within a function, block (within curly braces), or function argument. The local variable could be auto or static. Consider the below program,

void test(int x, int y)
{
    int a;
}

In the above program, a, x and y are local variables. They are only accessible within the test function.

2. Static Variable:

A static variable can have a block, function, or file scope (internal linkage). A static variable preserves its previous value and it is initialized at compilation time when memory is allocated. By default static variable initialize with 0.

#include <stdio.h>

//Static variable
//data2 have file scope
static int data2;


int main()
{
    //Static variable
    //scope only main function
    static int data1;

    return 0;
}

 

3. Global Variable:

Non-static variables declared outside the function are called global variables. A global variable is not limited to any function or file it can be accessed by any function or outside of the file. By default global variable is initialized with 0.

#include<stdio.h>

int data; // global variable

int main()
{
    return 0;
}

 

If you want to know more about the local, static and global variables you read the article, “Important points related to the local, static and global variable“.

 

Recommended Post:

9 comments

  1. For global variables, the declaration of integers may not necessarily define them, for example, you can redeclare an integer identifier `height’ by writing it twice in the global scope (at least in GCC):
    “`
    int hight;
    int hight;
    “`
    However, I am not sure which parts of the C standard specify this.

    1. In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. Each declaration of an identifier with no linkage denotes a unique entity.

Leave a Reply

Your email address will not be published. Required fields are marked *