Back to: C Tutorials For Beginners and Professionals
Variables in C Language with Examples
In this article, I am going to give a brief introduction to Variables in C Language with Examples. Please read our previous article discussing Unary vs. Binary vs. Ternary Operators in C. You will understand the following pointers in detail at the end of this article.
- Why do we need Variables in C Language
- What is the Relation Between Variable and Memory Locations?
- How do you access the data stored in a memory location?
- How Can We Set Identity to Memory Locations?
- What is a Variable in C Language?
- Rules for Variable Declaration in C
- Declaring and Initializing C Variables
- Why do we get garbage value by default in C?
- Types of Variables in C
Why do we need Variables in C Language?
Generally, if we want to execute a program, executing a program means to process the information or data, and to store data, we need memory in a computer or machine. Every machine has memory locations, and an address identifies every memory location. You can take the example of seating arrangement in a classroom or a theater. Just consider the seating arrangement as a memory location.
An address identifies a memory location. For a better understanding, please have a look at the below image. As you can see in the image below, 128, 572, 1024, 5098, etc. are one-one memory addresses. We can treat all the addresses as positive integer values.
What is the Relation Between Variable and Memory Locations?
Generally, if we want to store some information, suppose I want to store a value of 10 in the memory locations. Just consider a classroom; there is no restriction on where the students can sit. That means the students will go and sit randomly at different locations. In the same way, the value 10 that we want to store will also go and be stored randomly at a particular memory location. For a better understanding, please have a look at the below image. Here, you can see the value 10 is stored at a memory location whose address is 572.
How to Access the data?
Now, I want to access the data. Then how can we access it? How we can access the data means we will face the problems. The reason is that the data has been stored randomly at memory locations we cannot understand and identify. So, accessing becomes very difficult after storing the information. So, what we should do before storing the information is set the identity to the memory location, and then, using the identity, we need to access the data from the memory location. And this is where Variables come into the picture.
How Can We Set Identity to Memory Locations?
Before storing the information, we must first set the identity to the memory location. The following is the syntax to declare a variable by setting the identity of the memory location in the. First, we need to write the data type followed by the identifier.
Syntax: data_type Identifier;
Example: int a; //Here, the integer is the data type, and the identifier can be any name, and here we set it as a. So, whenever we declare a variable, it gets memory allocated, and to that memory location, the identity is set as shown in the below image.
Here, “a” is a named memory location to the location 10344. Later, we can store an element in the memory location, identified by the identifier “a” as follows.
a = 10; //Here, the value is 10, and we are setting this value into a memory location identified by a, as shown in the image below.
For example, in theater, every seat has some unique number, and when you come, you will sit in a particular seat allocated to you. Later, if they want to access it, they can easily do so.
What is a Variable in C Language?
A name that is given for any computer memory location is called a variable. The purpose of the variable is to store some data. The user will access it by the variable name, and the compiler will access it by the address. So, a variable is a named location in a memory where a program can manipulate the data. This location is used to hold the value of the variable.
In C programming, variables are used to store data which can be manipulated during the execution of a program. Each variable in C has a specific type, which determines the size and layout of the variable’s memory, the range of values stored within that memory, and the set of operations that can be applied to the variable.
Scope: The scope of a variable determines where it can be accessed. Variables can be local (inside a function or block), global (outside of all functions), or static.
Lifetime: The lifetime of a variable refers to the period during which the variable exists in memory. Local variables exist while the function or block executes, whereas global variables exist for the program’s execution.
Storage Classes: C has different storage classes for variables, like auto, register, static, and extern, which define the visibility, lifetime, and/or memory location of the variables.
Rules for Variable Declaration in C:
- A variable name must begin with a letter or underscore.
- Variables are case-sensitive
- They can be constructed with digits and letters.
- No special symbols are allowed other than underscores.
- sum, height, _value are some examples of the variable name
Declaring and Initializing C variable:
- Variables should be declared in the C program before use.
- Memory space is not allocated for a variable during declaration. It happens only on the variable definitions.
- Variable initialization means assigning a value to the variable.
How to Declare a Variable in C?
Declaration tells the compiler about the data type and size of the variable. The variable can be declared many times in a program. The variable declaration specifies the name and type of the variable.
Syntax: data_type variable_name;
Example: int x, y, z;
Here, x, y, and z are variable names, and int is the data type that specifies that x, y, and z can only store integer-type values. In our next article, we will discuss Data Types in detail.
Defining a Variable in C:
When we declare a variable in C#, it stores some garbage value by default. Here, garbage value means an unexpected value (it might be zero also), so after the declaration, when we assign some value to the variable. It is called Variable Initialization. Let us see how to initialize a variable in C.
Syntax: data_type variable_name;
variable_name = value;
Example: int x, y;
x = 50, y = 30; //Here, x is defined with a value of 50, and y is defined with a value of 30
Why do we get garbage value by default in C?
In C programming, when a variable is declared but not initialized, it often contains a “garbage value” by default. This occurs because of the following reasons:
- No Default Initialization: In C, variables are not automatically initialized to a default value when declared. This differs from other programming languages that may initialize variables to a default value (like zero for integers in Java).
- Memory Allocation: When a variable is declared, C allocates memory for that variable but does not clear or overwrite the existing data in that memory location. Therefore, the variable contains previously stored data at that memory address.
- Efficiency: Automatically initializing variables to a default value would require additional instructions and processing time. C is designed to be a low-level, efficient language, giving the programmer control over memory management. This design choice includes not spending extra cycles on initializing memory that the programmer might overwrite anyway.
- Undefined Behavior: Accessing uninitialized variables is considered an undefined behavior in C. It can lead to unpredictable results and bugs in the program. It’s considered good practice in C programming to always initialize variables before use.
To avoid garbage values and potential issues, always initialize variables in C before their first use is recommended. This can be done either at the point of declaration or before the variable is used in any computation or operation.
Variable Initialization in C:
Defining a variable with a value at the time of its declaration is known as variable initialization in C. So, we can say that Declaration + Definition = Initialization;
Syntax: data_type variable_name = value;
Example: int x = 0;
Note: Initializing a variable with zero after declaration is always a good programming practice. Here’s a simple example to illustrate these concepts:
#include <stdio.h> int globalVar = 50; // Global variable int main() { int localVar = 10; // Local variable printf("Global Variable: %d\n", globalVar); printf("Local Variable: %d\n", localVar); return 0; }
In this example, globalVar is a global variable accessible from anywhere in the program, while localVar is a local variable accessible only within the main function.
Types of Variables in C Language
In C programming, variables are used to store data, and their type defines the kind of data the variable can hold. Here are the main types of variables in C:
Basic Types:
- int: For integers. Examples include int age = 25;.
- float: For floating-point numbers (numbers with a decimal point). Example: float temperature = 36.6;.
- double: For double-precision floating-point numbers. It’s like float but can store double the number of digits. Example: double distance = 12345.6789;.
- char: For characters. Example: char initial = ‘A’;.
Derived Types:
- Arrays: A collection of elements of the same type. Example: int numbers[5]; defines an array of five integers.
- Pointer: A variable that stores the memory address of another variable. Example: int *p; is a pointer to an integer.
- Structure: Allows you to combine data items of different kinds. Example: struct {int id; char name[100];} student;.
- Union: Similar to structures but with different functionality. All members of a union share the same memory location.
Enumeration Type (enum):
- Used to define variables that can only take one out of a small set of possible values. Example: enum color { red, green, blue };.
Void Type:
- Indicates the absence of a value. It is often seen in the context of functions that return no value.
Typedef Defined Types:
- Allows you to give a new name to an existing type. Example: typedef unsigned char BYTE;.
In the next article, I will discuss Types of Variables in C Language with examples. In this article, I explain Variables in C Language with examples, and I hope you enjoy this variable in C Language with Examples article. I would like to have your feedback. Please post your feedback, questions, or comments about these Variables in the C Language article.
Best example!!