C Programming Tutorial for Beginners

What Are Variables in C Language? Examples, Rules, Types, Scope, Declaration

Introduction

variables in c

In this write-up (part of our C Programming Tutorial for Beginners), we are going to talk about the variables in C. The things we are going to cover here include:

  • What are variables in C language?

  • Types of variables in C

  • Examples

  • Declaration of variables in C

  • Scope of C variables

  • Rules for naming variables

  • Use of variables

And more…

What are Variables in C Language?

In C, a variable is a container for storing data that can be manipulated or used by the program. Variables have a name, a data type, and a value.

Using the variables, the programmers can be on their path to writing dynamic and flexible code. The common uses of variables include data storage, performing mathematical calculations, controlling the flow of the program, passing data between functions, and managing memory.

Types of Variables in C

There are several types of variables in C language that can be used to store different kinds of data. 

1. Integers (int) 

Used to store whole numbers. 

Integers can be signed (positive or negative) or unsigned (positive only). 

For example, "int x = 42;" would create an integer variable called "x" with the value of 42.

2. Floating-point (float)

Used to store decimal numbers. 

Floating-point variables can represent numbers with a fractional part. 

For example, "float y = 3.14;" would create a floating-point variable called "y" with the value of 3.14.

3. Double precision (double)

Similar to floating-point variables, but with more precision. 

Double-precision variables can represent decimal numbers with greater precision than floats. 

For example, "double z = 3.14159265359;" would create a double precision variable called "z" with the value of 3.14159265359.

4. Characters (char): 

Used to store single characters, such as letters or symbols. 

For example, "char c = 'A';" would create a character variable called "c" with the value of 'A'.

5. Booleans (bool)

Used to store either true or false. 

Booleans are typically used for conditional statements and comparisons. 

For example, "bool isTrue = true;" would create a boolean variable called "isTrue" with the value of true.

6. Pointers (pointer)

Used to store memory addresses. 

Pointers are used to reference other variables or objects in memory. 

For example, "int *p = &x;" would create a pointer variable called "p" that points to the memory address of the integer variable "x".

Examples of Variables in C

In C programming, you can declare and use different types of variables, depending on the data you want to store. 

Here are some examples of variables in C:

Integer variables example

int age = 25;

 

Character variables example

char first_initial = 'J';

 

Floating-point variables example

float height = 1.75;

 

Double variables example

double pi = 3.14159;

 

Boolean variables example

bool is_raining = true;

 

Pointer variables example

int *ptr = &age;

How to Declare Variables in C Programming?

Let’s understand the declaration of variables in C language with syntax and examples.

Syntax

data_type variable_name;

Where data_type is the type of the variable you want to declare, and variable_name is the name you want to give to the variable.

Example 1

For example, if you want to declare a variable to store an integer value called age, you can use the following code:

int age;

Example 2

If you want to declare a variable in C programming to store a floating-point value called salary, you can use the following code:

float salary;

How to Declare and Initialize Variables at Same Time?

You can also declare and initialize variables at the same time. To do this, you can use the following syntax:

Syntax

data_type variable_name = value;

Where value is the initial value you want to assign to the variable. 

Example 1

For example, to declare and initialize an integer variable called x with the value of 5, you can use the following code:

int x = 5;

Example 2

Similarly, to declare and initialize a floating-point variable called y with the value of 3.14, you can use the following code:

float y = 3.14;

How to Declare Multiple Variables in C?

You can also declare multiple variables in C language (of the same data type) in a single line by separating them with commas. 

Example

int a, b, c;

This declares three integer variables: a, b, and c.

Note: Variable names in C programming language must start with a letter, underscore, or dollar sign, and can contain letters, digits, underscores, and dollar signs. C is a case-sensitive language, so age and Age are two different variable names.

How to Change Value of Variable in C?

To change the value of a variable in C programming, you can assign a new value to the variable using the assignment operator (=). 

Example

int num = 5;   // Declare and initialize a variable 'num' with value 5

num = 10;      // Assign a new value 10 to the variable 'num'

In the above example, the variable num is first initialized with a value of 5, and then its value is changed to 10 using the assignment operator.

How to Add Variables in C?

You can also perform arithmetic operations on variables and then assign the result to the same or another variable. 

Example

int x = 5;
int y = 3;
int z;
z = x + y;     // Add the values of 'x' and 'y' and store the result in 'z'
x = x * 2;     // Multiply the value of 'x' by 2 and store the result back in 'x'

In the above example, we add the values of x and y and store the result in a new variable z. We then multiply the value of x by 2 and store the result back in the same variable x.

It's important to remember that the data type of the variable should match the data type of the value being assigned to it. Otherwise, you may encounter unexpected results or errors.

Scope of Variables in C Language

The scope of variables in C refers to the region of the program where the variable is visible and can be accessed. In other words, it determines the part of the program where the variable can be used.

When a variable is declared in C, it is only accessible within a certain area of the program, known as its scope. You must have a clear idea of the scope and lifetime of variables in C programming.

There are three types of variable scope in C:

1. Global Scope

A global variable is declared outside of any function or block and can be accessed from any part of the program. Global variables have file scope and are visible to all functions within the same file.

Example:

#include 
int globalVar = 10; // global variable
void printGlobalVar() {
    printf("The value of globalVar is %d\n", globalVar);
}
int main() {
    printf("The value of globalVar is %d\n", globalVar);
    printGlobalVar();
    return 0;
}
Output:
The value of globalVar is 10
The value of globalVar is 10

2. Local Scope 

A local variable is declared inside a block or function and can only be accessed from within that block or function. Once the block or function is exited, the local variable is destroyed and its memory is released.

Example:

#include 
int main() {
    int localVar = 5; // local variable
    printf("The value of localVar is %d\n", localVar);
    return 0;
}
Output:
The value of localVar is 5

3. Function Parameter Scope

Function parameters have the same scope as local variables. They are declared inside the function and can only be accessed from within the function.

Example:

#include 
void printVar(int x) {
    printf("The value of x is %d\n", x);
}
int main() {
    int localVar = 5;
    printVar(localVar);
    return 0;
}
Output:
The value of x is 5

It's important to note that variables with the same name can have different scopes. For example, a local variable with the same name as a global variable will have local scope and will be unrelated to the global variable.

Rules for Naming Variables in C

It is important to follow certain rules for naming variables in C to ensure that your code is easy to read and maintain. 

Here are some rules to keep in mind:

  • Variable names can only contain letters, digits, and underscores. They cannot contain spaces, special characters, or punctuation marks.

  • Variable names must start with a letter or an underscore. They cannot start with a digit.

  • Variable names are case-sensitive. This means that 'myVariable' and 'MyVariable' are two different variables.

  • Use descriptive names that reflect the purpose or content of the variable. This helps make your code more readable and understandable.

  • Avoid using reserved keywords as variable names. There are a number of reserved keywords in C that have specific meanings and uses in the language. Examples of reserved keywords include 'int', 'char', 'if', 'else', and 'while'.

  • Use camelCase convention or underscore_separated convention for variable names. In camelCase, the first word is lowercase, and the subsequent words are capitalized, e.g. myVariableName. In underscore_separated convention, words are separated by underscores, e.g. my_variable_name.

What are Local Variables in C?

Local variables are defined within a function or a block of code, and they are only accessible within that function or block. These variables are typically used to store temporary values or intermediate results in a function. 

When a function is called, its local variables are created, and when the function returns, the local variables are destroyed. 

Local variables in C language have a limited scope, which means that they can only be accessed within the function or block in which they are defined.

Example

void myFunction() {
    int x = 10; // x is a local variable
    printf("The value of x is %d\n", x);
}
int main() {
    myFunction();
    // printf("%d", x); // Error: x is not defined in main
    return 0;
}

In this code, x is a local variable defined within the myFunction function. It cannot be accessed outside of the function, as shown by the commented-out printf statement in the main.

What Are Global Variables in C?

Global variables are defined outside of any function or block, and they are accessible from any part of the program. These variables have a global scope, which means that they can be accessed by any function or block in the program. 

The global variables in C language have a lifetime that extends throughout the entire execution of the program.

Example

#include <stdio.h>
int x = 10; // x is a global variable
void myFunction() {
    printf("The value of x is %d\n", x);
}
int main() {
    myFunction();
    printf("The value of x is %d\n", x);
    return 0;
}

In this code, x is a global variable defined outside of any function. It can be accessed by both myFunction and main, as shown by the two printf statements. 

Note that global variables can be modified by any part of the program, which can make them difficult to track and debug in large programs.

What is the Use of Variables in C?

The role or use of variables in C programming is to store and manipulate data. They allow programmers to write flexible and dynamic code by allowing the value of the variable to change during program execution.

Here are some common uses of variables in C:

  • Data storage

Variables are used to store data in memory, allowing the program to access and manipulate that data as needed.

  • Calculation

These are used to store values that are used in calculations or expressions. It helps the program to perform complex mathematical operations.

  • Control flow

Variables in C are also useful when it comes to controlling the flow of a program by storing the state of a condition or loop. 

For example, a loop counter variable can control how many times a loop should run.

  • Parameter passing

You can pass data between functions using the C variables. It enables the functions to operate on data stored in other parts of the program.

  • Memory management

Furthermore, you can use the variables in C programming to allocate and manage memory dynamically.

Size of Variables in C Programming Language

The size of variables in C depends on the data type of the variable. The following data types are available for variables:

  • char: occupies 1 byte of memory.

  • int: typically occupies 2 or 4 bytes of memory (depending on the system architecture and the compiler used).

  • float: occupies 4 bytes of memory.

  • double: occupies 8 bytes of memory.

  • long: typically occupies 4 or 8 bytes of memory (depending on the system architecture and the compiler used).

  • long long: typically occupies 8 bytes of memory.

It is important to note that the actual size of a variable of a particular data type may vary depending on the system architecture and the compiler used. 

For example, on a 32-bit system, an int variable may occupy 2 bytes of memory, while on a 64-bit system, the same variable may occupy 4 bytes of memory. 

Similarly, a long variable may occupy 4 bytes of memory on a 32-bit system and 8 bytes of memory on a 64-bit system.

Variables in C Language PDF

You can easily and quickly download our free PDF on C variables to learn the concepts locally on your mobile or desktop. 

Download Now

FAQs Related to C Variables

Here are a few of the frequently asked questions about C variables:

1. What Are External Variables in C?

An external variable in C language is a global variable that is defined in one source file and is declared in another source file. 

External variables can be accessed from any part of the program, just like normal global variables. However, they are typically used to share data between multiple source files in a program.

Here's an example of how to define and declare an external variable in C:

// File1.c
#include 
int count; // Define an external variable called "count"
int main() {
   count = 5; // Set the value of count
   return 0;
}
// File2.c
#include 
extern int count; // Declare the external variable "count"
void printCount() {
   printf("The value of count is %d\n", count); // Access the external variable
}

In this example, the external variable "count" is defined in File1.c and declared in File2.c using the extern keyword. The function printCount in File2.c can access the value of the count by using the declared variable.

Note that the declaration of an external variable must match the definition in terms of its data type, name, and scope. If these do not match, the program will generate a linking error at compile time. 

Additionally, it's generally good practice to minimize the use of external variables and to use other means of sharing data between functions, such as function arguments and return values.

2. What is the Use of Static Variables in C?

A static variable in C language is a type of local variable that retains its value between function calls. 

Unlike normal local variables, which are created and destroyed each time a function is called, a static variable is created once when the function is first called, and it retains its value between subsequent function calls.

Here are some common uses of static variables in C:

  • Maintaining state between function calls: If you have a function that needs to maintain some state or keep track of some data between calls, you can use a static variable to do so. 

For example, consider a function that counts the number of times it has been called:

int getCount() {
    static int count = 0;
    count++;
    return count;
}

In this example, the static variable count is used to keep track of the number of times the getCount function has been called. The value of the count is retained between function calls, so each time the function is called, it returns a higher value.

  • Limiting the scope of a variable: If you have a local variable that you only want to be accessible within a specific function, you can make it static. This limits the scope of the variable to the function in which it is defined, and prevents other functions from accessing or modifying it.

void myFunction() {
    static int x = 0;
    // do something with x
}

In this example, the static variable x is only accessible within the myFunction function, and cannot be accessed or modified by other functions in the program.

  • Reducing code complexity: If you have a large program with many functions, it can be difficult to keep track of all the variables that are in use. By making some variables static, you can reduce the number of variables that are in the global scope, which can make it easier to manage the code and avoid naming conflicts.

It's worth noting that static variables can be a source of bugs if they are not used carefully. Because their values persist between function calls, they can sometimes lead to unexpected behavior if their value is not properly initialized or updated. 

Additionally, if you rely too heavily on static variables, it can make it difficult to understand and maintain the code.

3. What are Automatic Variables in C?

An automatic variable in C language is a local variable that is created when a function is called and is destroyed when the function returns. 

These variables are the most common type of variable in C, and they are created automatically when a function is called without any additional keywords or modifiers.

4. What is the difference between constants and variables in C?

Constants and variables in C language are used to store values, but they differ in how their values can be modified during program execution.

A constant is a value that cannot be modified during program execution. Constants are declared with the keyword "const" and they are assigned a value during initialization. 

Once a constant is initialized, its value cannot be changed throughout the program. Constants are useful for defining values that should not be changed, such as mathematical constants or fixed values that are used throughout the program.

Example of a constant declaration in C:

const int MAX_VALUE = 100;

A variable, on the other hand, is a value that can be modified during program execution. Variables are declared with a data type and a name, and they can be assigned a value during initialization or at any point during the program's execution. 

Variables are used to store values that can change throughout the program, such as user input or intermediate calculation results.

Example of a variable declaration in C:

int count = 0;

For other concepts of this language, make sure to check our full C Programming Tutorial for Beginners, where we are covering everything in detail, including:

And more…

Did you find this article helpful?