0% found this document useful (0 votes)
25 views17 pages

2.0 C Variables and Constants

Uploaded by

mrwhiza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views17 pages

2.0 C Variables and Constants

Uploaded by

mrwhiza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

C Variables

••

A variable in C language is the name associated with some memory location to store
data of different types. There are many types of variables in C depending on the scope,
storage class, lifetime, type of data they store, etc. A variable is the basic building block
of a C program that can be used in expressions as a substitute in place of the value it
stores.
What is a variable in C?
A variable in C is a memory location with some name that helps store some form of
data and retrieves it when required. We can store different types of data in the variable
and reuse the same variable for storing some other data any number of times.
They can be viewed as the names given to the memory location so that we can refer to
it without having to memorize the memory address. The size of the variable depends
upon the data type it stores.
C Variable Syntax
The syntax to declare a variable in C specifies the name and the type of the variable.
data_type variable_name = value; // defining single variable
or
data_type variable_name1, variable_name2; // defining multiple variable
Here,
data_type: Type of data that a variable can store.

• variable_name: Name of the variable given by the user.
• value: value assigned to the variable by the user.
Example
int var; // integer variable
char a; // character variable
float fff; // float variables
Note: C is a strongly typed language so all the variables types must be specified before
using them.

Variable Syntax Breakdown

There are 3 aspects of defining a variable:


1. Variable Declaration
2. Variable Definition
3. Variable Initialization
1. C Variable Declaration
Variable declaration in C tells the compiler about the existence of the variable with the
given name and data type.When the variable is declared, an entry in symbol table is
created and memory will be allocated at the time of initialization of the variable.
2. C Variable Definition
In the definition of a C variable, the compiler allocates some memory and some value to
it. A defined variable will contain some random garbage value till it is not initialized.
Example
int var;
char var2;
Note: Most of the modern C compilers declare and define the variable in single step.
Although we can declare a variable in C by using extern keyword, it is not required in
most of the cases. To know more about variable declaration and definition, click here.
3. C Variable Initialization
Initialization of a variable is the process where the user assigns some meaningful value
to the variable when creating the variable.
Example
int var = 10; // variable declaration and definition (i.e. Vairable
Initialization)
Difference between Variable Initialization and Assignment
Initialization occurs when a variable is first declared and assigned an initial value. This
usually happens during the declaration of the variable. On the other hand, assignment
involves setting or updating the value of an already declared variable, and this can
happen multiple times after the initial initialization.
Example
int a=10; //Variable initialization
a=10; //assignment

How to use variables in C?


The below example demonstrates how we can use variables in C language.
C
// C program to demonstrate the
// declaration, definition and
// initialization
#include <stdio.h>

int main()
{
// declaration with definition
int defined_var;

printf("Defined_var: %d\n", defined_var);

// assignment
defined_var = 12;

// declaration + definition + initialization


int ini_var = 25;

printf("Value of defined_var after assignment: %d\n", defined_var);


printf("Value of ini_var: %d", ini_var);

return 0;
}

Output
Defined_var: 0
Value of defined_var after assignment: 12
Value of ini_var: 25

Rules for Naming Variables in C


You can assign any name to the variable as long as it follows the following rules:
1. A variable name must only contain alphabets, digits, and underscore.
2. A variable name must start with an alphabet or an underscore only. It cannot
start with a digit.
3. No white space is allowed within the variable name.
4. A variable name must not be any reserved word or keyword.

C Variable Types
The C variables can be classified into the following types:
1. Local Variables
2. Global Variables
3. Static Variables
4. Automatic Variables
5. Extern Variables
6. Register Variables
1. Local Variables in C
A Local variable in C is a variable that is declared inside a function or a block of code.
Its scope is limited to the block or function in which it is declared.
Example of Local Variable in C
C
// C program to declare and print local variable inside a
// function.
#include <stdio.h>

void function()
{
int x = 10; // local variable
printf("%d", x);
}

int main() { function(); }

Output
10

In the above code, x can be used only in the scope of function(). Using it in the main
function will give an error.
2. Global Variables in C
A Global variable in C is a variable that is declared outside the function or a block of
code. Its scope is the whole program i.e. we can access the global variable anywhere in
the C program after it is declared.
Example of Global Variable in C
C
// C program to demonstrate use of global variable
#include <stdio.h>

int x = 20; // global variable

void function1() { printf("Function 1: %d\n", x); }

void function2() { printf("Function 2: %d\n", x); }

int main()
{
function1();
function2();
return 0;
}

Output
Function 1: 20
Function 2: 20

In the above code, both functions can use the global variable as global variables are
accessible by all the functions.
Note: When we have same name for local and global variable, local variable will be
given preference over the global variable by the compiler.
For accessing global variable in this case, we can use the method mention here.

3. Static Variables in C
A static variable in C is a variable that is defined using the static keyword. It can be
defined only once in a C program and its scope depends upon the region where it is
declared (can be global or local).
The default value of static variables is zero.
Syntax of Static Variable in C
static data_type variable_name = initial_value;
As its lifetime is till the end of the program, it can retain its value for multiple function
calls as shown in the example.
Example of Static Variable in C
C
// C program to demonstrate use of static variable
#include <stdio.h>

void function()
{
int x = 20; // local variable
static int y = 30; // static variable
x = x + 10;
y = y + 10;
printf("\tLocal: %d\n\tStatic: %d\n", x, y);
}

int main()
{
printf("First Call\n");
function();
printf("Second Call\n");
function();
printf("Third Call\n");
function();
return 0;
}

Output
First Call
Local: 30
Static: 40
Second Call
Local: 30
Static: 50
Third Call
Local: 30
Static: 60

In the above example, we can see that the local variable will always print the same
value whenever the function will be called whereas the static variable will print the
incremented value in each function call.
Note: Storage Classes in C is the concept that helps us to determine the scope,
lifetime, memory location, and default value (initial value) of a variable.

4. Automatic Variable in C
All the local variables are automatic variables by default. They are also known as auto
variables.
Their scope is local and their lifetime is till the end of the block. If we need, we can use
the auto keyword to define the auto variables.
The default value of the auto variables is a garbage value.
Syntax of Auto Variable in C
auto data_type variable_name;
or
data_type variable_name; (in local scope)
Example of auto Variable in C
C
// C program to demonstrate use of automatic variable
#include <stdio.h>

void function()
{
int x = 10; // local variable (also automatic)
auto int y = 20; // automatic variable
printf("Auto Variable: %d", y);
}
int main()
{
function();
return 0;
}

Output
Auto Variable: 20

In the above example, both x and y are automatic variables. The only difference is that
variable y is explicitly declared with the auto keyword.
5. External Variables in C
External variables in C can be shared between multiple C files. We can declare an
external variable using the extern keyword.
Their scope is global and they exist between multiple C files.
Syntax of Extern Variables in C
extern data_type variable_name;
Example of Extern Variable in C
----------myfile.h------------
extern int x=10; //external variable (also global)

----------program1.c----------
#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", x);
}
In the above example, x is an external variable that is used in multiple C files.
6. Register Variables in C
Register variables in C are those variables that are stored in the CPU register instead
of the conventional storage place like RAM. Their scope is local and exists till
the end of the block or a function.
These variables are declared using the register keyword.
The default value of register variables is a garbage value.
Syntax of Register Variables in C
register data_type variable_name = initial_value;
Example of Register Variables in C
C
// C program to demonstrate the definition of register
// variable
#include <stdio.h>

int main()
{
// register variable
register int var = 22;
printf("Value of Register Variable: %d\n", var);
return 0;
}

Output
Value of Register Variable: 22

NOTE: We cannot get the address of the register variable using addressof (&) operator
because they are stored in the CPU register. The compiler will throw an error if we try
to get the address of register variable.

Constant Variable in C
Till now we have only seen the variables whose values can be modified any number of
times. But C language also provides us a way to make the value of a variable
immutable. We can do that by defining the variable as constant.
A constant variable in C is a read-only variable whose value cannot be modified once it
is defined. We can declare a constant variable using the const keyword.
Syntax of Const Variable in C
const data_type variable_name = value;
Note: We have to always initialize the const variable at the definition as we cannot
modify its value after defining.
Example of Const Variable in C
C
// C Program to Demonstrate constant variable
#include <stdio.h>

int main()
{
// variable
int not_constant;

// constant variable;
const int constant = 20;

// changing values
not_constant = 40;
constant = 22;

return 0;
}

Output
Constants in C

The•• constants in C are the read-only variables whose values cannot be modified once they are
declared in the C program. The type of constant can be an integer constant, a floating pointer
constant, a string constant, or a character constant. In C language, the const keyword is used
to define the constants.
In this article, we will discuss about the constants in C programming, ways to define constants
in C, types of constants in C, their properties and the difference between literals and
constants.
What is a constant in C?
As the name suggests, a constant in C is a variable that cannot be modified once it is declared
in the program. We can not make any change in the value of the constant variables after they
are defined.
How to Define Constant in C?
We define a constant in C language using the const keyword. Also known as a const type
qualifier, the const keyword is placed at the start of the variable declaration to declare that
variable as a constant.
Syntax to Define Constant
const data_type var_name = value;

Example of Constants in C
C
// C program to illustrate constant variable definition
#include <stdio.h>

int main()
{

// defining integer constant using const keyword


const int int_const = 25;

// defining character constant using const keyword


const char char_const = 'A';

// defining float constant using const keyword


const float float_const = 15.66;

printf("Printing value of Integer Constant: %d\n",


int_const);
printf("Printing value of Character Constant: %c\n",
char_const);
printf("Printing value of Float Constant: %f",
float_const);

return 0;
}

Output
Printing value of Integer Constant: 25
Printing value of Character Constant: A
Printing value of Float Constant: 15.660000
One thing to note here is that we have to initialize the constant variables at declaration.
Otherwise, the variable will store some garbage value and we won’t be able to change it. The
following image describes examples of incorrect and correct variable definitions.

Types of Constants in C
The type of the constant is the same as the data type of the variables. Following is the list of
the types of constants
• Integer Constant
• Character Constant
• Floating Point Constant
• Double Precision Floating Point Constant
• Array Constant
• Structure Constant
We just have to add the const keyword at the start of the variable declaration.
Properties of Constant in C
The important properties of constant variables in C defined using the const keyword are as
follows:
1. Initialization with Declaration
We can only initialize the constant variable in C at the time of its declaration. Otherwise, it
will store the garbage value.
2. Immutability
The constant variables in c are immutable after its definition, i.e., they can be initialized only
once in the whole program. After that, we cannot modify the value stored inside that variable.
C
// C Program to demonstrate the behaviour of constant
// variable
#include <stdio.h>

int main()
{
// declaring a constant variable
const int var;
// initializing constant variable var after declaration
var = 20;

printf("Value of var: %d", var);


return 0;
}

Output
In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^
Difference Between Constants and Literals
The constant and literals are often confused as the same. But in C language, they are different
entities and have different semantics. The following table lists the differences between the
constants and literals in C:
Constant Literals

Constants are variables that cannot be modified Literals are the fixed values that define
once declared. themselves.

Constants are defined by using the const


They themselves are the values that are assigned
keyword in C. They store literal values in
to the variables or constants.
themselves.

We cannot determine the address of a literal


We can determine the address of constants.
except string literal.

They are lvalues. They are rvalues.

Example: const int c = 20. Example: 24,15.5, ‘a’, “Geeks”, etc.

Defining Constant using #define Preprocessor


We can also define a constant in C using #define preprocessor. The constants defined using
#define are macros that behave like a constant. These constants are not handled by the
compiler, they are handled by the preprocessor and are replaced by their value before
compilation.
#define const_name value
Example of Constant Macro
C
// C Program to define a constant using #define
#include <stdio.h>
#define pi 3.14

int main()
{

printf("The value of pi: %.2f", pi);


return 0;
}

Output
The value of pi: 3.14
Note: This method for defining constant is not preferred as it may introduce bugs and make the
code difficult to maintain.

Different ways to declare variable as constant in C


•••
There are many different ways to make the variable as constant in C. Some of the popular
ones are:
1. Using const Keyword
2. Using Macros
3. Using enum Keyword
1. Using const Keyword
The const keyword specifies that a variable or object value is constant and can’t be modified
at the compilation time.
Syntax
const data_type variable_name = initial_value;
Example
The below example demonstrates use of the const keyword.
C
// C program to demonstrate const specifier
#include <stdio.h>
int main()
{
const int num = 1;

num = 5; // Modifying the value


return 0;
}
It will throw as error like:
error: assignment of read-only variable ‘num’
2. Using Macros
We can also use Macros to define constant, but there is a catch. Since Macros are handled by
the pre-processor(the pre-processor does text replacement in our source file, replacing all
occurrences of ‘var’ with the literal 5) not by the compiler. Hence it wouldn’t be
recommended because Macros doesn’t carry type checking information and also prone to
error. In fact not quite constant as ‘var’ can be redefined like this.
Syntax
#define name value
Example
The below example demonstrates use of macros (#define).
C
// C program to demonstrate the problems
// in 'Macros'
#include <stdio.h>

#define var 5
int main()
{
printf("%d ", var);

#ifdef var
#undef var

// redefine var as 10
#define var 10
#endif

printf("%d", var);
return 0;
}

Output
5 10
Note: preprocessor and enum only works as a literal constant and integers constant
respectively. Hence they only define the symbolic name of constant. Therefore if you need a
constant variable with a specific memory address use either ‘const’ or ‘constexpr’ according to
the requirement.

3. Using enum Keyword


Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to
integral constants, that make a program easy to read and maintain.
Example
The below example demonstrates use of the enum keyword.
C
// C program to illustrate the use of enums to declare
// constant
#include <stdio.h>

// In C internally the default


// type of 'var' is int
enum VARS { var = 42 };
// where mytype = int, char, long etc.
// but it can't be float, double or
// user defined data type.
int main()
{
printf("The value of var: %d", var);

return 0;
}

Output
The value of var: 42
Note: The data types of enum are of course limited as we can see in above example.

Scope rules in C

The•• scope of a variable in C is the block or the region in the program where a variable is
declared, defined, and used. Outside this region, we cannot access the variable, and it is treated
as an undeclared identifier.
• The scope is the area under which a variable is visible.
• The scope of an identifier is the part of the program where the identifier may
directly be accessible.
• We can only refer to a variable in its scope.
• In C, all identifiers are lexically(or statically) scoped.
Example
C
// C program to illustrate the scope of a variable
#include <stdio.h>

int main()
{
// Scope of this variable is within main() function
// only.
int var = 34;

printf("%d", var);
return 0;
}

// function where we try to access the var defined in main()


void func() { printf("%d", var); }

Output
solution.c: In function 'func':
solution.c:15:28: error: 'var' undeclared (first use in this function)
void func() { printf("%d", var); }
Here, we tried to access variable names var As we can see that if we try to refer to the variable
outside its scope, we get the above error.
Types of Scope Rules in C
C scope rules can be covered under the following two categories:
1. Global Scope
2. Local Scope
Let’s discuss each scope rule with examples.
1. Global Scope in C
The global scope refers to the region outside any block or function.
• The variables declared in the global scope are called global variables.
• Global variables are visible in every part of the program.
• Global is also called File Scope as the scope of an identifier starts at the beginning of
the file and ends at the end of the file.
Example
C
// C program to illustrate the global scope
#include <stdio.h>

// variable declared in global scope


int global = 5;

// global variable accessed from


// within a function
void display()
{
printf("%d\n", global);
}

// main function
int main()
{
printf("Before change within main: ");
display();

// changing value of global


// variable from main function
printf("After change within main: ");
global = 10;
display();
}

Output
Before change within main: 5
After change within main: 10
Linkage of Variables in Global Scope
Global variables have external linkage by default. It means that the variables declared in the
global scope can be accessed in another C source file. We have to use the extern keyword for
that purpose.
Example of External Linkage
file1.c
C
// filename: file1.c
#include <stdio.h>

// Define the global variable


int a;

// Define the function to use the global variable


void myfun()
{
printf("%d\n", a);
}

main.c
C
// filename: main.c
#include <stdio.h>

// Declare the external variable and function


extern int a;
void myfun();

int main(void)
{
// Initialize the global variable
a = 2;

// Call the function to print the value of 'a'


myfun();

return 0;
}

Output
2
Note: To restrict access to the current file only, global variables can be marked as static.

2. Local Scope in C
The local scope refers to the region inside a block or a function. It is the space enclosed between
the { } braces.
• The variables declared within the local scope are called local variables.
• Local variables are visible in the block they are declared in and other blocks
nested inside that block.
• Local scope is also called Block scope.
• Local variables have no linkage.
Example
C
// C program to illustrate the local scope
#include <stdio.h>

// Driver Code
int main()
{
{
int x = 10, y = 20;
{
// The outer block contains
// declaration of x and
// y, so following statement
// is valid and prints
// 10 and 20
printf("x = %d, y = %d\n", x, y);
{
// y is declared again,
// so outer block y is
// not accessible in this block
int y = 40;

// Changes the outer block


// variable x to 11
x++;

// Changes this block's


// variable y to 41
y++;

printf("x = %d, y = %d\n", x, y);


}

// This statement accesses


// only outer block's
// variables
printf("x = %d, y = %d\n", x, y);
}
}
return 0;
}

Output
x = 10, y = 20
x = 11, y = 41
x = 11, y = 20

You might also like