Unit-3: Understanding The Scope of Functions
Unit-3: Understanding The Scope of Functions
Unit-3: Understanding The Scope of Functions
#include <stdio.h>
int main () {
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
Global Variables
Global variables are defined outside a function, usually on top of the program.
Global variables hold their values throughout the lifetime of your program and they
can be accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration. The following
program show how global variables are used in a program.
#include <stdio.h>
/* global variable declaration */
int g;
int main () {
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
A program can have same name for local and global variables but the value of local
variable inside a function will take preference. Here is an example −
Formal Parameters
Formal parameters, are treated as local variables with-in a function and they take
precedence over global variables. Following is an example −
#include <stdio.h>
/* global variable declaration */
int a = 20;
int main () {
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %d\n", a);
c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0;
}
/* function to add two integers */
int sum(int a, int b) {
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}
When the above code is compiled and executed, it produces the following result −
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
Type Qualifiers
C provide three type qualifiers
1. Constant variable 2.volatile variable 3.restrict variable
Constant and volatile can be applied to any variables, but restrict qualifier may only
applied to pointer.
Constant variable:
Constants are also like normal variables. But, only difference is, their
values can’t be modified by the program once they are defined.
They refer to fixed values. They are also called as literals.
They may be belonging to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Ex:- const int a;
Here a is constant and its value cannot be changed
Int const *x;
Int the example x is a constant.
#include<stdio.h>
Int main()
{
Const int x=10;
Printf(“%d”,x);
Int x=20;
Printf(“%d”,x);
}
Output:-
Error:The value of x cannot be changed.
Volatile variable:-
Variable that can be changed at any time by external programs or the same
program are called as volatile variables.
The keyword volatile is placed before declaration.
To make variable value changeable by the current program and
unchangeable by other programs, declare the variable as volatile and
const.
Syntax:
Volatile int x;
Volatile const int y;
Volatile int *z;
In the above example the value of ‘x’ can be changed by any program at
any time and variable ‘y’ can be changed in the current program but not
external programs.
Restrict variable:
In the C programming language (after 99 standard), a new keyword is introduced
known as restrict.
Restrict keyword is mainly used in pointer declarations as a type qualifier for
pointers.
It doesn’t add any new functionality. It is only a way for programmer to inform
about an optimizations that compiler can make.
When we use restrict with a pointer ptr, it tells the compiler that ptr is the only
way to access the object pointed by it and compiler doesn’t need to add any
additional checks.
If a programmer uses restrict keyword and violate the above condition, result is
undefined behavior.
restrict is not supported by C++. It is a C only keyword.
int main(void)
{
int a = 50, b = 60, c = 70;
use(&a, &b, &c);
printf("%d %d %d", a, b, c);
return 0;
}
Run on IDE
Output:
120 130 70
Storage Classes in C
Storage Classes are used to describe about the features of a variable/function. These
features basically include the scope, visibility and life-time which help us to trace
the existence of a particular variable during the runtime of a program.
for(ch=getchar();isdigit(ch); )
……;
As a general rule, a function call cannot be on the left side of an
assignment.
A statement such as
swap(x,y) =100; /*incorrect statement */ is wrong.
The compiler will falg it as an error will not compile a program that
Contain it.
When you write programs your functions will be of three types.
The first type is simply computational
These functions are specially designed to perform operations ion
their argument’s and return a value based on that operation.
A computational function “pure” function.
Examples are the standard library functions sqrt() and sin() ,which
compute the square root and sine of their arguments.
The second type of function manipulates information and returns a
value that simply indicates the success or failure of that
manipulation.
An example is the library function fclose() which closes a file.
If the close operation is successful, the functions returns 0,it returns
EOF if an error occurs.
The last type of function has explicit return value.
In essence the function is strictly procedural and produce no value.
An example is exit (), which terminates the program.
All function that do not return values should be declared as returning
type void.
By declaring a function as void you keep it from being used in an
expression, thus preventing accidental misuse.
Sometimes function that really don’t produce an interesting result
return something anyway.
For example, printf() returns the number of characters written.
Yet, it is unusual to find a program that actually checks this.
In other words although all functions except those of type void
return values you don’t have to use return value for anything,
A common question concerning function return values is, “Don’t I
have to assign this to some variable since a value is being returned?”
the answer is no.
If there is no assignment specified, the return value is simply
discarded.
Consider the following program which uses the function mul( ):
#include<stdio.h>
Int mul(int a, int b);
Int main(void)
{
int x,y,z;
x=10;y=20;
z=mul(x,y); /* 1 */
printf(“%d”,mul(x,y)); / * 2 * /
mul(x,y); /* 3 */
return 0;
}
Int mul(int a,int b)
{
return a*b;
}
In line 1, the return value of mul() is assigned to z.
In line2, the return value is not actually assigned, but it is used by
printf().
Finally, in line 3,the return value is lost because it is neither assigned
to another variable nor used as part of an expression.
Returning pointers
Although functions that return pointers are handled just like any
other type of function.
Pointers are neither integers nor unsigned integers.
One reason for this distinction is that pointer arithmetic is relative to
the base type.
In general each time a pointer is incremented (decremented), it
points to the next (or previous) item of its type.
Since the length of different datatypes may differ the compiler must
know what type of data the pointer is pointing to.
For this reason a function that returns a pointer must declare
explicitly what type of pointer it is returning.
For example you should not use a return type of int * to return a
char * pointer.
In few cases function will need to return a generic pointer,in this
case the function return type must be specified as void *.
To return a pointer a function must be declared as having a pointer
return type.
Where, returnType is the type of the pointer that will be returned by the
function functionName.
And param list is the list of parameters of the function which is optional.
In the following example we are declaring a function by the name getMax that
takes two integer pointer variable as parameter and returns an integer pointer.
#include <stdio.h>
// function declaration
int main(void) {
// integer variables
int x = 100;
int y = 200;
// pointer variable
return 0;
// function definition
int *getMax(int *m, int *n) {
return m;
else {
return n;
Output:
#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;
}
Output
Example2:
#include<stdio.h>
#include<conio.h>
void main()
{
int a=100, b=200;
clrscr();
swap(a, b); // passing value to function
printf("\nValue of a: %d",a);
printf("\nValue of b: %d",b);
getch();
}
Output
value of a: 200
Value of b: 100
Call by value:
In call by reference, original value is modified because we pass reference
(address).
Here, address of the value is passed in the function, so actual and formal arguments
shares the same address space. Hence, value changed inside the function, is
reflected inside as well as outside the function.
Example2:
#include<stdio.h>
#include<conio.h>
void main()
{
int a=100, b=200;
clrscr();
swap(&a, &b); // passing value to function
printf("\nValue of a: %d",a);
printf("\nValue of b: %d",b);
getch();
}
Output
Value of a: 200
Value of b: 100
Calling function with arrays:
Just like variables, array can also be passed to a function as an argument. In this
guide, we will learn how to pass the array to a function using call by value and call
by reference methods.
1. C – Array
2. Function call by value in C
3. Function call by reference in C
#include <stdio.h>
void disp( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int x=0; x<10; x++)
{
/* I’m passing each element one by one using subscript*/
disp (arr[x]);
}
return 0;
}
Output:
abcdefghij
Passing array to function using call by reference
When we pass the address of an array while calling a function then this is called
function call by reference. When we pass an address as an argument, the function
declaration should have a pointeras a parameter to receive the passed address.
#include <stdio.h>
void disp( int *num)
{
printf("%d ", *num);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<10; i++)
{
/* Passing addresses of array elements*/
disp (&arr[i]);
}
return 0;
}
Output:
1234567890
How to pass an entire array to a function as an argument?
In the above example, we have passed the address of each array element one by
one using a for loop in C. However you can also pass an entire array to a function
like this:
Note: The array name itself is the address of first element of that array. For
example if array name is arr then you can say that arr is equivalent to the &arr[0].
#include <stdio.h>
void myfuncn( int *var1, int var2)
{
/* The pointer var1 is pointing to the first element of
* the array and the var2 is the size of the array. In the
* loop we are incrementing pointer so that it points to
* the next element of the array on each increment.
*
*/
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);
/*increment pointer for next element fetch*/
var1++;
}
}
int main()
{
int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(var_arr, 7);
return 0;
}
Output: