Variables in C and C++ | A Complete Guide for Beginners

When we hear about variables, we tend to think about mathematical formulas and questions in which variables are unknown values or quantities limited to some numbers. But, in the C/C++ programming language, variables connote a different meaning. In mathematical terms, we use representations of variables such as x or y that indicates an unknown value that we are supposed to find. Here, variables in the C and C++ programming language are the basic units, which help us to build C Programs. So, without wasting time, start exploring C/C++ variables.

Stay updated with the latest technology trends while you're on the move - Join DataFlair's Telegram Channel

What are Variables in C and C++?

A C/C++ program performs many tasks and operations that help you to resolve many problems by storing values into computer memory. But, how does the compiler understand the names given to these values? A variable helps to specify the existence of these values by defining and declaring them.

Variables-in-C-and-C++

In simple words, a variable is a storage space associated with a unique name to identify them. When you want to store some data on your system in the computer memory, is it possible for you to be able to remember these memory addresses? The answer is no, and that is the reason why we use variables.

Variables in C/C++ programming help us to store values depending upon the size of the variable. With the help of variables, we can decide what amount and type of data store in a variable. When you assign a data type and name to some space in the memory, variables are defined.

Variables reserve some memory in the storage space, that you can access later in the program. By declaring a variable, you inform the operating system to reserve memory indicated by some name. i.e. variable_name.

Enhance your fundamental skills with Operators in C

Naming a Variable in C/C++

You need to follow some rules, before naming a variable in C and C++:

  1. A variable must not start with a digit.
  2. A variable can begin with an alphabet or an underscore.
  3. Variables in C and C++ are case-sensitive which means that uppercase and lowercase characters are treated differently.
  4. A variable must not contain any special character or symbol.
  5. White spaces are not allowed while naming a variable.
  6. Variables should not be of the same name in the same scope.
  7. A variable name cannot be a keyword.
  8. The name of the variable should be unique.

Let’s see some examples of both valid and invalid variable names.

Valid variable names

ticketdata
_ticketdata
ticket_data

Invalid variable names

56ticketdata
ticket@data
ticket data

Variable Definition

A variable definition in C and C++ defines the variable name and assigns the data type associated with it in some space in computer memory. After giving its definition, this variable can be used in the program depending upon the scope of that variable.

By defining a variable, you indicate the name and data type of the variable to the compiler. The compiler allocates some memory to the variable according to its size specification.

Learn Data Types in C and C++ with Example in Just 4 mins.

Rules for Defining Variables in C and C++

  1. Must contain data_type of that variable.
    Example: int start;
    float width;
    char choice;
  2. The variable name should follow all the rules of the naming convention.
  3. After defining the variable, terminate the statement with a semicolon otherwise it will generate a termination error. Example: int sum;
  4. The variable with the same data type can work with a single line definition. Example: float height, width, length;

Defining Variables in C and C++ with Example

int var;

Here, a variable of integer type with the variable name var is defined. This variable definition allocates memory in the system for var.

Another example,

char choice ;

When we define this variable named choice, it allocates memory in the storage space according to the type of data type in C, i.e., character type.

Variable Declaration

There is a huge difference between defining a variable and declaring a variable.

By declaring a variable in C and C++, we simply tell the compiler that this variable exists somewhere in the program. But, the declaration does not allocate any memory for that variable.

Declaration of variable informs the compiler that some variable of a specific type and name exists. The definition of variable allocates memory for that variable in the program.

So, it is safe to say that the variable definition is a combination of declaration and memory allocation. A variable declaration can occur many times but variable definition occurs only once in a program, or else it would lead to wastage of memory.

Variable Initialization

Variable initialization means assigning some value to that variable. The initialization of a variable and declaration can occur in the same line.

int demo = 23;

By this, you initialize the variable demo for later use in the program.

Before we start to discuss types of variables, you should know Functions and their importance in C

Types of Variables in C and C++

There are 5 types of Variables in C/C++; let’s discuss each variable with example.

Types of Variables in C and C++

1. Local Variables

The scope of local variables lies only within the function or the block of code. These variables stay in the memory till the end of the program.

Example of Local Variable in C
#include <stdio.h>
int main()
{

printf("Welcome to DataFlair tutorials!\n\n");

int result = 5; //local variable
printf("The result is %d \n", result);
return 0;
}

Code on Screen-

 Local Variables in C with example

Output-

Output of Local Variables in C

Example of Local Variable in C++
#include <iostream>
using namespace std;
 
int main()
{
cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;
 
int result = 5; //local variable
cout<<"The result is: "<< result<<endl;
return 0;
}

Code on Screen-

Example of Local Variables in C++

Output-

Output of Local Variables in C++

2. Global Variables

A global variable has a global scope, that is, this variable is valid until the end of the program. These variables are available to all the functions in that program.

Let us now see an example to understand the difference between local and global variables in C and C++.

Example of Global Variables in C
#include <stdio.h>
int sumf();
int sum = 2; //global variable
int main ()
{

printf("Welcome to DataFlair tutorials!\n\n");

int result =5; //local variable
sumf();
return 0;
}
int sumf()
{
printf("\n Sum is %d \n", sum);
printf("\n The result is %d \n", result);
}

Code on Screen-

Global Variables in C with examples

When we compile this program,

As the variable result is not defined globally, that is why the code is not compiled, and an error occurs when we use this variable out of that function.

Let us correct it, by making the result as the global variable in C/C++.

#include <stdio.h>
int sumf();
int sum = 2; //global variable
int result =5; //global variable
int main ()
{

printf("Welcome to DataFlair tutorials!\n\n");

sumf();
return 0;
}
int sumf()
{
printf("\n Sum is %d \n", sum);
printf("\n The result is %d \n", result);
}

Code on Screen-

global variable in C with Example

Output-

Output of global variable in C

Example of Global Variables in C++

Let us take the same example in C++ to understand the difference between a local and a global variable:

#include <iostream>
using namespace std;
 
int sumf();
int sum = 2; // global variable
int main ()
{
 
cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;;
int result =5; //local variable
sumf();
return 0;
}
int sumf()
{
cout<<"Sum is: "<< sum <<endl;
cout<<"The result is: "<< result <<endl;
}

Error-

Error in Global variable in C++

In this way, we can implement a global variable in C++

#include <iostream>
using namespace std;
 
int sumf();
int sum = 2; //global variable
int result =5; //global variable
int main ()
{
cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;
sumf();
return 0;
}
int sumf()
{
cout<<"Sum is: "<< sum <<endl;
cout<<"The result is: "<< result <<endl;
}

Code on Screen-

Example of Global Variables in C++

Output-

Output of Global Variables in C++

3. Static Variables

Static variable retains its value within the function calls. ‘static’ keyword is used to define a static variable. A static variable can preserve its value, and you can not initialize a static variable again.

Example of Static Variables in C

Let us now see how a local variable and static variable are different.

#include <stdio.h>
void statf();
int main ()
{

printf("Welcome to DataFlair tutorials!\n\n");

int i;
for(i = 0; i < 5; i++)
{
statf();
}
}
void statf()
{ 
int a = 20; //local variable 
static int b = 20; //static variable 
a = a + 1; 
b = b + 1; 
printf("\n Value of a %d\t,Value of b %d\n",a ,b); 
}

Code on Screen-

Example of Static Variables in C

Output-

Output of Static Variables in C

Example of Static Variables in C++

Let us now see how a local variable and static variable are different in C++:

#include <iostream>
using namespace std;
void statf();
int main ()
{
cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;
int i;
for(i = 0; i < 5; i++)
{
statf();
}
}
void statf()
{ 
int a = 20; //local variable 
static int b = 20; //static variable 
a = a + 1; 
b = b + 1; 
cout<<"Value of a: " << a << " ,Value of b: "<< b <<endl; 
}

Code on Screen-

Example of Static Variables in C++

Output-

Output of Static Variables in C++

With every function call, static variable uses the preserved value and increment the value of a variable, whereas a local variable re-initializes the value every time function calls takes place.

4. Automatic Variables

The variable declared inside a block is called an automatic variable.

The automatic variables in C are different from the local variables, automatic variable allocates memory upon the entry to that block and frees the occupied space when the control exits from the block.

‘auto’ keyword defines an automatic variable.

Example

auto int var = 39;

5. External Variables

We use ‘extern’ keyword to increase the visibility of the program. An extern variable is available to other files too.

The difference between global and extern variable is, a global variable is available anywhere within the file or program in which global variable declares but an extern variable is available for other files too.

Note: Variables with keyword ‘extern’ are only declared; they are not defined. Also, initialization of extern keywords can also be considered as its definition.

extern int var;

It means that extern variable var is available or valid in the program and in the other files too.

Note: Declaration of var takes place and not the definition.

Summary

In this tutorial, we focused on all significant points related to variables. Follow these rules for variables in C and C++,

  1. Every variable uses some memory in the storage space when it is defined not declared.
  2. Initializing a variable can be done along with a definition.
  3. There are various types of variables that C support and these variables are categorized based on their scope.

It’s time to learn and execute the datatypes in C with example

Please provide suggestions for improvement and queries in the comment section.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.