Variables in C: Basics, Types, and Rules

Updated on October 21, 2024

Article Outline

A variable in C language is associated with some memory location in the computer system to store data of different types. Variables allow for the easy management and manipulation of data stored in the computer memory. Understanding the declaration, scope, and types of variables is crucial for effective programming. This article will delve into the rules of variable declaration and how they are interpreted by the compiler in C language.

What is a Variable?

A variable is a named storage location in memory with a value that can be modified during the program execution. Each variable in C has a specific data type. A data type determines the kind of data it can store and a scope that defines where it can be accessed within the program. The value of a variable can be changed during the program execution.

 

The following program demonstrates the variable in C language:

 

Program

#include <stdio.h> #include <stdio.h> int main(){ int num1, num2, sum ; printf("Enter the first") ; scanf("%d", &num1) ; printf("Enter the second number") ; scanf("%d",&num2) ; sum = num1 + num2 ; printf("The sum of %d ", sum) ; return 0 ; }

Output

Enter the first 10 Enter the second number 2 The sum of 12
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Declaration of Variable in C

Here is the syntax of the declaration variable in C language:

 

data_type variable_name = value ; // defining single variable

 

Data_type variable_name1, variable_name2 ;// defining multiple variable

 

Here is the explanation:

 

  • data_type: It defines the type of variable that can be stored.
  • variable_name: Name of the variable which the user defines.
  • Value: It is assigned to the variable by the user.

 

Example

 

int var;    // integer variable

char a;     // character variable

float fff;  // float variables

Initialisation of Variables in C

In C programming, initialisation assigns an initial value to a variable when declared. Proper initialisation is crucial to avoid undefined behaviour and ensure variables hold predictable and useful values before they are used in calculations or operations.

 

Syntax of Initialisation of Variable in C:

 

<data type> <variable-name = value>;

The following program demonstrates the variable initialisation in the C language:

 

Program

#include <stdio.h> int main() { int int_var = 10; float float_var = 3.14f; double double_var = 2.71828; char char_var = 'C'; int array_var[ 10] = {1, 2, 3,4,5,6,7,8,9 ,10}; char string_var[] = "Hello, World!"; printf("Int Variable  %dn", int_var); printf("Float Variable: %.2fn", float_var); printf("Double Variable: %.5f n", double_var); printf("Character Variable: %cn", char_var); for(int i = 0;i< 10;i++){ printf("%dn",array_var[i]) ; } printf("String variable: %sn", string_var); return 0; }

Output

Int Variable  10 Float Variable: 3.14 Double Variable: 2.71828 Character Variable: C 1 2 3 4 5 6 7 8 9 10   String variable: Hello, World!

Types of Variables in C

The C language provides various variable varieties for different programming purposes:

 

  • Local Variables
  • Global Variables
  • Static Variables
  • External variables
  • Automatic Variables

Local Variables

Local variables are declared inside a function or block with the keyword local. They are accessible only within that function or block and not visible outside of it. Local variables are crucial for managing only relevant data within a specific scope.

 

The following program demonstrates the local variables:

 

Program

#include <stdio.h> void calculateSum() { int num1 = 5; int num2 = 10; int sum; sum = num1 + num2; printf("Sum: %dn", sum); }  int main() { calculateSum();  int x = 20; int y = 30; int total = x + y;  printf("Total: %dn", total);  return 0; }

Output

Sum: 15 Total: 50

Global Variables

A Global variable in C language. It is a variable declared outside the function or block of source code. Global variable scope is available in the whole program. Simply , a C developer can access the global variable anywhere in the program.

 

The following program demonstrates the global variable in the C language:

 

Program

#include <stdio.h> int globalCount = 0; void incrementCount() { globalCount++; }  void printCount() { printf("Global Count: %dn", globalCount); }  int main() { printCount(); incrementCount(); incrementCount(); printCount(); return 0; }

Output

Global Count: 0 Global Count: 2

Static Variables

Static variables in C have a lifespan that extends throughout the program’s lifetime. However, their visibility and scope can vary depending on where they are declared. The static variables retain values between function calls or restrict their visibility to a particular file or function.

 

The following program demonstrates the static variable:

 

Program

#include <stdio.h> static int fileScopeVar = 100; void countFunctionCalls() { static int callCount = 0; callCount++; printf("Function called %d timesn", callCount); }  void displayFileScopeVar() { printf("File scope variable: %dn", fileScopeVar); }  void modifyFileScopeVar() { fileScopeVar += 50; }  int main() { printf("Demonstrating static variables within functions:n"); countFunctionCalls(); countFunctionCalls(); countFunctionCalls();  printf("nDemonstrating static variables at file scope:n"); displayFileScopeVar(); modifyFileScopeVar(); displayFileScopeVar();  return 0; }

Output

Demonstrating static variables within functions: Function called 1 times Function called 2 times Function called 3 times  Demonstrating static variables at file scope: File scope variable: 100 File scope variable: 150

External Variables

The extern keyword declares an external variable or function defined in another file. This does not allocate any memory or initialise the variable. It simply informs the compiler about the existence and type of the function variable and functions across multiple files in a modular program.

 

The following program demonstrates the external variables:

 

Program

#include <stdio.h> extern int globalVar; int globalVar = 10; void incrementGlobalVar(); void printGlobalVar(); void incrementGlobalVar() { globalVar += 5; } void printGlobalVar() { printf("Value of globalVar: %dn", globalVar); } int main() { printf("Initial value:n"); printGlobalVar(); incrementGlobalVar(); printf("After incrementing:n"); printGlobalVar(); return 0; }

Output

Initial value: Value of globalVar: 10 After incrementing: Value of globalVar: 15

Automatic Variables

Automatic variables are local variables automatically created and destroyed when a function is called and exited. They are sometimes called ‘stack variables’ because they are typically stored on the stack.

 

The following program demonstrates the automatic variable:

 

Program

#include <stdio.h> void displayAutoVariable() { auto int x = 10; printf("Value of x inside displayAutoVariable: %dn", x); x++; }  int main() { auto int y = 20; printf("Value of y inside main: %dn", y); displayAutoVariable(); printf("Value of y after calling displayAutoVariable: %dn", y); return 0; }

Output

Value of y inside main: 20 Value of x inside displayAutoVariable: 10 Value of y after calling displayAutoVariable: 20

Rules of Naming Variables

Naming variables correctly in C is crucial for writing readable and maintainable source code. Let’s understand the rule of naming variables in language:

 

  • Variable names must begin with letters (a-z, A-Z) or an underscore (_).
  • Variable names are case-sensitive. This means “variable”, “Variable” and “VARIABLE” are considered different identifiers.
  • Variable names cannot use C-reserved keywords or standard library function names.
  • The variable names should be concise yet descriptive. Avoid names that are too short or excessively long.

Also Read: String Concatenation in C

Conclusion

In this article, we learned about variables in the C language. Variables are essential elements in programming languages used to store data in memory. They must be declared before use, specifying their types, such as int, float, or char, and can be initialised with a value at declaration. We also learned about the storage classes in the C language. C developers must know about the variables in C to write effective source code.  Understanding these aspects of variables is key to writing efficient and effective C code, as it enables programmers to manage data accurately and optimise program performance.

FAQs
We can ensure variables are initialised during declaration, use initialisation functions if necessary, and perform checks before using them in critical operations. For example  int value = 0; if (value == 0) {     // Perform operations safely }
We can declare a variable by specifying its type followed by its name. For Example    int age; float salary; char grade;
It is the process of assigning value to a variable at its declaration. For example    int age = 25; float salary = 50000.0; char grade = 'A';
Local Scope:  A variable is accessible only within the function or block where it is declared.    Global Scope: If declared as an extern keyword, a variable is accessible from any function within the same file or other files. 
The variables can be used in an expression to perform operations. For example    int a = 5; int b = 10; int sum = a + b;

Updated on October 21, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved