top

Search

C Tutorial

.

UpGrad

C Tutorial

What is Variables in C

Introduction

In C language, variables can be considered containers that store data values such as numbers, characters, etc. 

Understanding variables is essential to programming as it allows you to store and manipulate data while executing different programs. Variables help store temporary or permanent values required for your program to run calculations, make decisions and interact with the user. 

This tutorial will give you an in-and-out understanding of what variables are in C programming, their types, use cases, and everything relevant. 

So let’s get started!

Importance of Understanding Variables in C

In C, a variable is a named storage location in the computer's memory where you can store values. It acts as a container that holds the value of a specific data type, such as integers, floating-point numbers, characters, etc.

Here are some prime reasons why you should have a sound understanding of variables in C programming. 

1. Storing and manipulating data

Variables allow you to store different types of data and perform operations with them. For example, you can store user input, perform mathematical calculations, or manipulate strings using variables.

2. Tracking program state

Variables are essential for tracking the state of your program. You can use variables to store intermediate results, update their values based on program logic and use those values later in the program.

3. Enabling dynamic behaviours

With variables, you can create programs with dynamic behaviours. Variables can change their values during program execution based on user input, program logic, or external factors. This allows your programs to adapt and respond to different situations.

4. Facilitating code organisation

Variables help you to organise your codes by adding meaningful names to different data values. This makes your code more readable and easier to understand, both for yourself and for others who might read or maintain your code.

However, please note that to use variables in C, you need to declare them first. A variable declaration specifies its name and data type. For example -

int age; // Declaring an integer variable named "age"
float pi; // Declaring a floating-point variable named "pi"
char initial; // Declaring a character variable named "initial"

Once declared, you can assign values to variables using the assignment operator (=). For example -

int age = 25; // Assigning a value of 25 to the variable "age"
float pi = 3.14159; // Assigning a value of 3.14159 to the variable "pi"
char initial = 'J'; // Assigning the character 'J' to the variable "initial"

Variables can be used in expressions, passed as arguments to functions, and their values can be modified as your program executes.

Understanding variables and how to work with them is a fundamental concept in C programming, as it forms the basis for more complex operations and concepts. It allows you to store and manipulate data effectively, making your programs more powerful and versatile.

Aspects of defining a variable

Variables in C are defined through three aspects: variable definition, initialisation, and declaration. 

Variable Definition in C

The variable definition refers to the process of declaring a variable and allocating memory for it. It involves specifying the variable's name and data type. In C, a variable definition typically includes the storage class (optional), data type, and variable name. For example -

int age;          // Variable definition: "age" is an integer variable
float pi;        // Variable definition: "pi" is a floating-point variable
char initial;   // Variable definition: "initial" is a character variable

In the above examples, the variables ‘age’, ‘pi’, and ‘initial’ are defined with their respective data types (‘int’, ‘float’, and ‘char’).

Variable Initialization in C

Variable initialization involves assigning an initial value to a variable at the time of its declaration. Initialization is optional, and variables can be used without being initialised, but it's good practice to initialise variables to a known value before using them. You can initialise a variable using the assignment operator (‘=’). For example:

int age = 25;            // Variable initialization with an initial value of 25
float pi = 3.14159;    // Variable initialization with an initial value of 3.14159
char initial = 'J';    // Variable initialization with an initial value of 'J'

In the above examples, the variables ‘age’, ‘pi’, and ‘initial’ are not only defined but also initialised with specific values.

Variable Declaration in C

Declaration of variable in C refers to the process of introducing a variable by specifying its name and data type without allocating memory for it. It informs the compiler about the existence of a variable before it is used. A variable can be declared without initialization. For example -

extern int age;         // Variable declaration: "age" is an integer variable
extern float pi;       // Variable declaration: "pi" is a floating-point variable
extern char initial;  // Variable declaration: "initial" is a character variable

In the above examples, the variables ‘age’, ‘pi’, and ‘initial’ are declared using the ‘extern’ keyword. This informs the compiler that the memory for these variables will be allocated elsewhere, such as in another file.

Variable declaration is typically used when you want to use variables defined in other files or in a header file since variable declaration introduces a variable by specifying its name and data type without allocating memory.

Overview of C Variable Syntax

In C, the syntax is used for declaring variables and comprises multiple components such as data type, identifier, initialization, and semicolon. 

Data Type:

Every variable in C has to have a data type that helps specify the type of data the variable can hold. Some common data types in C include ‘int’ (for integers), ‘float’ (for floating-point numbers), ‘char’ (for characters), and ‘double’ (for double-precision floating-point numbers), among others.

Identifier:

An identifier is the name given to a variable. It can be any valid combination of letters (both uppercase and lowercase), digits, and underscores. The first character of an identifier must be a letter or an underscore. 

The identifier should also not be a reserved keyword in C (such as ‘int’‘float’, etc.). Choose meaningful and descriptive names for your variables to enhance code readability.

Initialization:

 Initialization is optional but recommended. It involves assigning an initial value to the variable at the time of declaration. Initialization can be done using the assignment operator (=). For example, ‘int age = 25;’

Semicolon: 

Each variable declaration statement in C must end with a semicolon (‘;’). The semicolon is used to indicate the end of the statement.

Below is an example of the syntax used to declare variables in C. 

#include <stdio.h>

int main() {
    // Variable declarations and initialization
    int age = 25;
    float pi = 3.14159;
    char initial = 'J';

    // Using the variables
    printf("My age is %d\n", age);
    printf("The value of pi is %f\n", pi);
    printf("My initial is %c\n", initial);

    return 0;
}

Here, in this example, 

  • The int variable age is declared and initialised with the value 25.

  • The float variable pi is declared and initialised with the value 3.14159.

  • The char variable initial is declared and initialised with the character 'J'.

  • The variables are then used in printf statements to display their values.

Also, note that it is a must to declare variables before you use them. 

How to Use Variables in C?

To use variables in C, you need to follow a four-stepped approach, which starts with Declaration, followed by Initialization and Assignment and ends with Usage. 

1. Variable Declaration: Start by declaring the variables with the appropriate data types and names. This informs the compiler about the existence of the variables. For example -

int age;          // Declaration of an integer variable named "age"
float pi;        // Declaration of a floating-point variable named "pi"
char initial;   // Declaration of a character variable named "initial"

2. Variable Initialization: Optionally, you can initialize the variables with initial values at the time of declaration. Initialization assigns a value to the variable. For example -

int age = 25;           // Initialization of "age" with a value of 25
float pi = 3.14159;   // Initialization of "pi" with a value of 3.14159
char initial = 'J';   // Initialization of "initial" with the character 'J'

3. Assignment: To assign a new value to a variable at any point in your program, you use the assignment operator (=). The new value replaces the existing value stored in the variable. For example -

age = 30;           // Assigning a new value of 30 to the variable "age"
pi = 3.14;           // Assigning a new value of 3.14 to the variable "pi"
initial = 'S';       // Assigning a new value of 'S' to the variable "initial"

4. Usage: You can use variables in expressions, statements, and function calls throughout your program. For example -

int newAge = age + 5;              // Using "age" variable in an expression
printf("My age is %d\n", age);     // Using "age" variable in printf statement
scanf("%f", &pi);                     // Using "pi" variable in scanf statement

In the above examples, we use the variables age and pi in an expression, a printf statement, and a scanf statement, respectively. You can perform mathematical calculations, display variables' values, or take user input using variables.

Also, remember that in C, variable names are case-sensitive. Therefore, age and Age are considered different variables.

Types of Variables in C

Based on characteristics, variables in C are of different types. Here are some major types of variables in C examples. 

1. Local Variables: 

Local variables are declared within a block of code, such as within a function. They are only accessible within the scope of the block where they are declared. Local variables comprise automated storage duration, which means they are generated when the block is entered and destroyed when the block is exited. 

2. Global Variables: 

The global variable in C is declared outside of any function or block. They are accessible from any part of the program and have a global scope. Global variables have static storage duration, meaning they are created at program startup and remain in memory until the program terminates. Global variables should be used with caution since they can lead to code complexity and make it harder to track dependencies.

3. Function Parameters: 

Function parameters are variables that are passed to a function during a function call. They allow you to pass values to functions and use them within the function's code. Function parameters act as local variables within the function and are initialised with the values passed in from the calling code.

4. Static Variables: 

Static variable in C have a local scope but retain their values between function calls. They are declared with the static keyword. Static variables have static storage duration, meaning they are created and initialised only once, and their values persist across multiple function calls. 

5. Constants: 

Constants are variables whose values cannot be changed once they are assigned. They are declared using the const keyword. Constants can improve code readability and maintainability by explicitly indicating that a value should not be modified. 

6. Pointer Variables: 

Pointer variables store memory addresses of other variables. They allow you to indirectly access and manipulate variables by referring to their memory locations. Pointers are declared using the ‘*’ symbol. Pointers play a crucial role in advanced C programming, enabling dynamic memory allocation, data structures, and more.

Conclusion

Finally, for a quick recap, a variable in C is a named storage location that is used for storing data during program execution. They have data types that determine the kind of data they can hold, i.e., integers, floating-point numbers, characters, etc. 

We discussed variable declaration and definition in C and learned that you must declare a variable before using them. Depending on the type ( local or global), the scope of variables in C also changes. 

Understanding variables is crucial as they allow you to store and manipulate data in programs. By following the syntax rules, declaring variables with the appropriate data types, and using them effectively, you can create dynamic and functional C programs.

On the other hand, upskilling with upGrad’s Data Science and Analytics Bootcamp will further offer you an edge to expand your knowledge and gain efficiency in programming.

FAQs

Q: What is a variable in C language?

Variable refers to the name provided to a storage location, which holds the value of the data stored. This may include, grades, height, income or your residential details. 

Q: What are the different types of variables?

Different types of variables in C include: Local, Global, Function, Static, Constants and Pointer variables in C.

Q: Are there any restrictions for using variable names in C?

Yes, there are several restrictions to ensure the correct usage of variables in C. For example, variable names are case-sensitive, and must contain only alpha-numeric characters and underscores, while it should not contain any spaces.

Leave a Reply

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