Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Variable in C?
3.
C Variable Syntax
4.
3 Aspects of Defining a Variable: Declaration, Definition, & Initialization
4.1.
1. Variable Declaration
4.2.
2. Variable Definition
4.3.
3. Variable Initialization
5.
How to Use Variables in C
5.1.
Assigning Values
5.2.
Using Variables in Calculations
5.3.
Updating Variables
6.
Rules for Naming Variables in C
6.1.
1. Letters and Digits
6.2.
2. Case Sensitivity
6.3.
3. Avoid Reserved Words
6.4.
4. Clarity and Meaning
6.5.
5. Keep It Short and Specific
7.
Example of Good Variable Names
8.
C Variable Types
8.1.
Local Variables
8.2.
C
8.3.
Global Variables: Example
8.4.
C
8.5.
Static Variables: Example
8.6.
C
8.7.
Automatic Variables: Example
8.8.
C
8.9.
Extern Variables: Example
8.10.
Register Variables: Example
8.11.
C
9.
Frequently Asked Questions
9.1.
What is the difference between local & global variables in C?
9.2.
Can I change the value of a constant variable in C?
9.3.
What is the purpose of register variables in C?
10.
Conclusion
Last Updated: May 18, 2024
Easy

C Variable Types

Author Rinki Deka
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Variables are a fundamental concept in programming, & they play a crucial role in the C language. A variable is a named storage location in a computer's memory that can hold a value. It allows you to store & manipulate data throughout your program. In C, variables have specific types that determine the kind of data they can store, such as integers, floating-point numbers, characters, & more. Understanding variables & their types is essential for writing effective C programs. 

C Variable Types

In this article, we will talk about the different variable types in C, their declaration & initialization, & how to use them in your code.

What is a Variable in C?

A variable in C programming is a named piece of memory where you can store data that your program might use or change. Think of it as a small box where information is kept. Each variable in C is defined with a specific type, which tells what kind of data it can hold. Types include integers for whole numbers, characters for individual letters or symbols, and other more complex types for larger or more precise data.

Variables are important because they let you store and work with data in your programs. For example, if you are creating a program that adds two numbers, each number will be stored in a variable. You can also change the data in a variable, which is why they are called variables - because the data can vary.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

C Variable Syntax

To use variables in C, you need to specify what type they are and give them a name. This process is called declaring a variable. The general syntax for declaring a variable in C is straightforward:

type variable_name;


Here, type is the data type of the variable, such as int for integers, float for floating-point numbers, char for characters, and so on. variable_name is the identifier chosen by you to refer to the variable.

For example, to declare an integer variable with the name age, you would write:

int age;


This statement tells the C compiler that there is a variable named age which will hold integer data. Once a variable is declared, you can store values in it and modify them as needed. Here's how you can initialize age with a value:

age = 25;


Now, age has a value of 25. You can change this value anytime by assigning a new value to it:

age = 30; // now age is 30


Declaring and initializing a variable can also be done in one step, which is often more efficient:

int age = 25;


This line of code does both actions at once: it declares age as an integer and initializes it with the value 25.

Variables must be declared at the beginning of a block of code (like at the start of a function) before they are used. This rule helps keep your programs organized and running correctly.

3 Aspects of Defining a Variable: Declaration, Definition, & Initialization

In C programming, working with variables involves three crucial steps: declaration, definition, and initialization. Understanding these steps is key to effectively managing and using variables in your programs.

1. Variable Declaration

Declaration is the first step where you tell the compiler about the variable and its type without necessarily assigning any value to it. For example:

int count;


Here, count is declared as an integer. At this point, it’s just a name with an associated type but no assigned value.

2. Variable Definition

When you define a variable, you are actually allocating memory for it. Definition can be just like declaration if no value is provided. However, it typically includes assigning a value to the variable, making it both a declaration and a definition. For instance:

int count = 10;

 

This line both defines and initializes count with the value of 10, allocating memory to store the integer and setting that memory to 10.

3. Variable Initialization

Initialization specifically refers to the process of assigning a value to a variable at the time of declaration or definition. The initial value can be a constant, another variable's value, or even an expression, as shown below:

int count = 10;
int new_count = count;  // Initialization using another variable
int total = count + 5;  // Initialization using an expression


Each of these steps plays a vital role in how a variable is handled in C. Properly declaring, defining, and initializing variables ensures that your program uses memory efficiently and behaves predictably.

How to Use Variables in C

Using variables in C allows you to manipulate data in a variety of ways, making your programs dynamic & responsive. Here’s a straightforward guide on how to effectively use variables within your C programs.

 

Assigning Values

Once you have declared and defined a variable, you can assign values to it at any point in your program. This is done using the assignment operator =. For example:

int age;
age = 21; // Assigning the value 21 to the variable age

Using Variables in Calculations

Variables can be used in mathematical operations, which allows your program to perform calculations and store the results. For example:

int length = 10;
int width = 5;
int area = length * width; // Calculates the area of a rectangle

Updating Variables

You can update the value of a variable by using it in an operation with itself. This is useful for counting or accumulating values:

int count = 0;
count = count + 1; // Increases count by 1

Input and Output with Variables:
C allows you to get user input and store it in variables using the scanf function, and display variable values using the printf function:

int number;
printf("Enter a number: ");
scanf("%d", &number); // Reads an integer input from the user and stores it in 'number'
printf("You entered: %d", number); // Displays the value of 'number'


Using these basic operations, variables can significantly enhance the interactivity and functionality of your C programs. They are essential tools for any programmer, enabling the storage and manipulation of data throughout the lifecycle of the software.

Rules for Naming Variables in C

Choosing the right names for your variables is important as it helps make your code easier to understand and maintain. In C, there are specific rules and best practices that should be followed when naming variables:

1. Letters and Digits

Variable names can include letters (both uppercase and lowercase), digits, and the underscore (_) character. However, a variable name must start with a letter or an underscore. For example, count, _count, and count1 are valid names, while 1count is not.

2. Case Sensitivity

C is case-sensitive, which means that age and Age are considered two different variables. It is important to be consistent with capitalization when using your variables.

3. Avoid Reserved Words

Do not use C keywords as variable names. Keywords like int, return, static, and break are part of the language syntax and using them as variable names can lead to errors in your program.

4. Clarity and Meaning

Choose names that clearly describe what the variable represents, making your code easier to read and understand. For example, instead of naming a variable n, name it numStudents if it is used to store the number of students.

5. Keep It Short and Specific

While it’s important to have descriptive names, they should also be concise. Long variable names can make your code crowded and harder to read. Aim for a balance between clarity and length.

Example of Good Variable Names

  • int totalCost;
     
  • char grade;
     
  • float averageScore;
     

Each of these names clearly tells what the variable is used for, which makes the code that uses them more readable.

C Variable Types

In C programming, variables are categorized based on their lifetime and scope. Understanding these types helps in organizing data efficiently and affects how data is accessed within your programs. Here are the main variable types in C:

Local Variables

Local variables are those declared within a function or a block and their scope is limited to that function or block only. Here is a simple example to illustrate how local variables work in C:

  • C

C

#include <stdio.h>

void updateScore() {
int score = 10; // score is a local variable
score = score + 5; // Updating the score within the function
printf("Updated score: %d\n", score); // Prints "Updated score: 15"
}

int main() {
updateScore(); // Calling the function that uses the local variable
// printf("%d", score); // This line would cause an error because score is not accessible here
return 0;
}

Output

Updated score: 15


In this example, the variable score is local to the function updateScore(). It is created when updateScore() starts and is destroyed when updateScore() ends. Trying to access score outside this function, like in the main() function, will result in an error because score does not exist there.

Local variables are useful for temporary calculations and operations within a function, as they help to keep your functions independent of each other, which can make your programs easier to manage and debug.

Global Variables: Example

Global variables in C are declared outside of any function, which means they can be accessed and modified by any function within the program. This can be particularly useful for data that needs to be shared across multiple functions. Here’s how you can use global variables effectively:

  • C

C

#include <stdio.h>

int counter = 0; // Global variable declaration

void incrementCounter() {
counter = counter + 1; // Access and modify the global variable
printf("Counter incremented to: %d\n", counter);
}

void resetCounter() {
counter = 0; // Reset the global variable to zero
printf("Counter reset to: %d\n", counter);
}

int main() {
incrementCounter(); // First increment of the counter
incrementCounter(); // Second increment of the counter
resetCounter(); // Reset the counter
return 0;
}

Output

Counter incremented to: 1
Counter incremented to: 2
Counter reset to: 0


In this example, counter is a global variable accessible throughout the program. The function incrementCounter() increases the value of counter by one each time it is called, and the function resetCounter() sets counter back to zero. Both functions operate on the same counter variable, demonstrating how global variables facilitate data sharing across different parts of a program.

Using global variables can simplify data management in some scenarios, but it's important to use them judiciously. Overuse of global variables can lead to code that is difficult to understand and maintain, as changes to the variable in one part of the program can affect other parts unexpectedly.

Static Variables: Example

Static variables in C have a unique characteristic: they maintain their value between function calls. This is different from local variables, which are reinitialized every time a function is called. Here's an example to demonstrate the behavior of static variables:

  • C

C

#include <stdio.h>

void preserveCount() {

   static int count = 0; // Static variable

   count += 1; // Increment the static variable by 1

   printf("Current count: %d\n", count);

}

int main() {

   preserveCount(); // Calls the function the first time

   preserveCount(); // Calls the function the second time

   preserveCount(); // Calls the function the third time

   return 0;

}

In this example, the count variable is declared as static within the function preserveCount(). This means that its value is not reset each time the function is called. The first call sets count to 1, and each subsequent call increases it by 1. Therefore, the output will be:

Current count: 1
Current count: 2
Current count: 3


Static variables are particularly useful when you need to keep track of the state or count events over several function calls without using global variables. They provide a method to store information while keeping it scoped within the function, protecting it from external modifications, and keeping it accessible across multiple invocations of that function.

Automatic Variables: Example

Automatic variables are the default type of variables in C when no other storage class specifier (like static or extern) is mentioned. They are created at the beginning of the execution of the block in which they are declared and are destroyed at the end of it. Here is how automatic variables are typically used in a C program:

  • C

C

#include <stdio.h>

void demoFunction() {
int autoVar = 10; // Automatic variable
printf("Value inside function: %d\n", autoVar);
autoVar += 5; // Modify the automatic variable
printf("Updated value inside function: %d\n", autoVar);
}

int main() {
demoFunction(); // Each call to this function creates a new instance of autoVar
// Trying to access autoVar here would result in an error because it's not visible outside demoFunction
return 0;
}

Output

Value inside function: 10
Updated value inside function: 15


In this example, autoVar is an automatic variable declared inside demoFunction(). Each time demoFunction() is called, autoVar is created anew, initialized with the value 10, and destroyed at the end of the function. This means that autoVar cannot retain its value between multiple calls to demoFunction() and is not accessible outside the function.

Automatic variables are useful for temporary calculations and data storage within a specific function. They help to ensure that the data is contained and managed within a limited scope, preventing it from affecting or being affected by other parts of the program.

Extern Variables: Example

Extern variables in C are used to access global variables from other files within the same project. They allow you to declare a variable in one file and then use it in another without redeclaring it. Here's how extern variables work with a simple example:

File 1: main.c

#include <stdio.h>
extern int globalVar; // Declare globalVar from another file
int main() {
    printf("The value of globalVar is: %d\n", globalVar); // Access globalVar
    return 0;
}


File 2: other.c

int globalVar = 100; // Define globalVar in this file


In this example, globalVar is declared as an extern variable in main.c, which indicates that its definition is located in another file. In other.c, globalVar is defined and assigned a value of 100. When main.c is compiled and executed, it can access globalVar without any errors because of the extern declaration.

Extern variables are particularly useful for sharing data across multiple source files in a C project. They provide a way to modularize your code and keep related variables organized in separate files while still allowing them to be accessed when needed.

Register Variables: Example

Register variables in C are stored in the CPU registers for faster access compared to variables stored in memory. However, the use of register variables is merely a hint to the compiler, and it may choose to ignore this suggestion. Here's an example to illustrate register variables:

  • C

C

#include <stdio.h>

int main() {

   register int i; // Declare i as a register variable

   int sum = 0;

   for (i = 1; i <= 10000; ++i) {

       sum += i;

   }

   printf("Sum of numbers from 1 to 10000: %d\n", sum);

   return 0;

}

Output

Sum of numbers from 1 to 10000: 50005000


In this example, the variable i is declared as a register variable inside the loop. The register keyword suggests to the compiler that i should be stored in a CPU register for faster access. However, whether i is actually stored in a register depends on the compiler and the optimization level used during compilation.

Register variables are typically used for frequently accessed variables in performance-critical sections of code. However, modern compilers are often smart enough to optimize variable storage automatically, making explicit use of register variables unnecessary in most cases.

Frequently Asked Questions

What is the difference between local & global variables in C?

Local variables are declared within a function & are only accessible within that specific function. They are created when the function is called & destroyed when the function exits. On the other hand, global variables are declared outside of any function & can be accessed from anywhere in the program. They have a global scope & remain in memory throughout the program's execution.

Can I change the value of a constant variable in C?

No, you cannot change the value of a constant variable once it is initialized. Constant variables are declared using the "const" keyword, which indicates that their value should not be modified after initialization. Attempting to change the value of a constant variable will result in a compilation error.

What is the purpose of register variables in C?

Register variables are used to request the compiler to store a variable in the CPU's register instead of memory, if possible. By storing frequently accessed variables in registers, the program's performance can be improved since accessing registers is faster than accessing memory. However, the compiler may ignore the request & decide the optimal storage location based on its optimization strategies.

Conclusion

In this article, we have learned about the different variable types in C & their characteristics. We explored local variables, which are confined to a specific function, & global variables, which have a program-wide scope. We also discussed static variables that retain their value between function calls, automatic variables that are automatically allocated & deallocated, external variables that are defined in one source file but can be referenced in another, & register variables that suggest storage in CPU registers for faster access. Understanding these variable types & their proper usage is crucial for writing efficient & organized C programs. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass