Sei sulla pagina 1di 25

Unit-3

Understanding the scope of functions


A scope in any programming is a region of the program where a defined variable
can have its existence and beyond that variable it cannot be accessed. There are
three places where variables can be declared in C programming language −
 Inside a function or a block which is called local variables.
 Outside of all functions which is called global variables.
 In the definition of function parameters which are called formal parameters.
Let us understand what are local and global variables, and formal parameters.
Local Variables
Variables that are declared inside a function or block are called local variables. They
can be used only by statements that are inside that function or block of code. Local
variables are not known to functions outside their own. The following example
shows how local variables are used. Here all the variables a, b, and c are local to
main() function.

#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.

// C program to use restrict keyword.


#include <stdio.h>

void use(int* a, int* b, int* restrict c)


{
*a += *c;
*b += *c;
}

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.

Storage classes in c divide into four types


1. Automatic storage class
2. Register storage class
3. Static storage class
4. External storage class

Automatic storage class:


By defining a variable as automatic storage class, it stored in the memory. The
default value of the variable will be garbage value. Scope of the variable is with in
block where it is defined and the life of the variable is until control remains with in
the block.
To define a variable as automatic storage class, the keyword auto is used.
Syntax: auto int I;
For ex:-
auto int a,b;
Note:The keyword auto is not mandatory because the default storage class in C is
auto.
#include<stdio.h>
void main()
{
auto int a,b;
a=5;
printf(“a=%d,b=%d”,a,b);
fun();
}
void fun()
{
auto int c=10;
printf(“%d\n”,c);
}
In the above program a and c values are displayed, b displays garbage value.
Register storage class:
 When a variable is declared as register it is stored in the cpu registers.
 The default value of the variable will be garbage value.
 Scope of the variable is within the block where it is defined
 Life of the variable is until the control remains with in the block.
 To define the variable as register storage class, the keyword register storage
class is used.
 If cpu cannot store the variables in CPU registers ,then variables are assumed
as auto and stored in the memory.
Syntax: register int y;
/*program to declare a variable as a register*/
#include<stdio.h>
void main()
{
register int j=1;
do{
printf(“%d”,j);
j++;
}while(j<=10)
}
Output:
1 2 3 4 5 6 7 8 9 10.
Static storage class:
 When a variable is declared as static, it is stored in the memory.
 The default value of the variable will be zero.
 Scope of the variable is within the block where it is defined.
 The life of the variable persists between different function calls.
 To define a variable as a static storage class, the keyword static is used.
 A static variable is initialized only once.it cannot be reinitialized.
Syntax: static int x;
/*program for static storage class*/
#include<stdio.h>
int main()
{
Static int b;
int a;
printf(“a=%d,b=%d”,a,b);
}
Output:-
a=garbage value b=0
Extern storage class:
 When a variable is declared as extern, it is stored in memory.
 The default value is initialized in to zero
 The scope of the variable is global
 The life of the variable is until the program execution come to end.
 To define the variable as extern storage class, the keyword extern is used.
 An extern variable is also a global variable.
#include<stdio.h>
Int main()
{
func1();
func2();
printf(“e in main=%d”,e);
}
func1()
{
extern int e;
printf(“e in func1=%d”,e);
}
func2()
{
Printf(“e in func2=%d”,e);
}
Output:
e in main=20
e in func1=20
e in func2=20

The Return statement:


 Return statement has two important uses.
 First, it causes an immediate exit from the function. That is, it causes
program execution to return to the calling code.
 Second, it can be used to return value.
 The following section examine how the return statement is applied.
Returning from a function:
 A function terminates execution and returns to the caller in two
ways.
 The first can also occurs when the last statement in the function has
executed, and conceptually the functions ending curly brace (}) is
encountered.
For example:
#include<stdio.h>
int sum(int a,int b)
int main()
{
Int a,b;
Printf(“enter the values for a and b”);
Scanf(“%d%d”,&a,&b);
Sum(a,b);
int sum(int x,int y)
{
int result;
result=x+y;
printf(“%d”,result);
}
In the above example the function sum() simply calculates the sum of two
numbers on the screen and then returns.
 Actually not many functions use this default method of terminating
their execution.
 Most of the function rely on the return to stop execution either
because a value must be returned or to make functions code simpler
and more efficient.
 A function may contain several return statements.
For example;
#include<stdio.h>
Int maxNum(int a,int b);
int main()
{
int a,b;
printf(“enter the values for a and b”);
scanf(“%d%d”,&a,&b);
m=maxNum(a,b);
return 0;
}
int maxNum(int a,int b)
{
if(a>b)
return a;
else
return b;
}
Returning values:
 All functions except those of type void return a value.
 This value is specified by the return statement.
 In C89, if a non-void function executes a return statement that does
not include a value then a garbage value is returned.
 This is to say the least, bad practice.in C99 (and c++), a non-void
function must use a return statement that return a value.
 However if execution reaches the end of a non-void function (that is
encounters the function’s closing curly base), a garbage value is
returned.
 Although this condition is not a syntax error, it is still fundamental
flaw and should be avoided.
 As long as a function is not declared as void, you can use it as an
operand in an expression.
 Therefore, each of the following expression is valid:
X=power(y);

If(max(x,y) > 100)


printf(“gerater”);

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.

Declaration of function that returns pointer


Following is the function declaration syntax that will return pointer.

returnType *functionName(param list);

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.

int *getMax(int *, int *);

Function that returns pointer


In the following example the getMax() function returns an integer pointer i.e., address of a
variable that holds the greater value.

#include <stdio.h>

// function declaration

int *getMax(int *, int *);

int main(void) {

// integer variables

int x = 100;

int y = 200;

// pointer variable

int *max = NULL;

max = getMax(&x, &y);

// print the greater value

printf("Max value: %d\n", *max);

return 0;

// function definition
int *getMax(int *m, int *n) {

if (*m > *n) {

return m;

else {

return n;

Output:

Max value: 200

Functions of type void:


 One of void’s uses is to explicitly declare functions that do not return
values.
 This prevents their use in any expression and helps avert accidental
misuse.
For example:
#include<stdio.h>
void display();
int main()
{
display();
}
void display()
{
printf(“a void function without return statement.”);
}
Output:
A void function without return statement.
Function Arguments:
 If a function to accept arguments, it must declare the parameters
that will receive the values of the arguments.
 Even though parameter perform the special task of receiving the
value of the arguments passed to the function, they behave like
any other local variables.
Call by value:

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by


the function parameter in stack memory location. If you change the
value of function parameter, it is changed for the current function only.
It will not change the value of variable inside the caller method such as
main().

Let's try to understand the concept of call by value in c language by the


example given below:

#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

Before function call x=100

Before adding value inside function num=100

After adding value inside function num=200

After function call x=100.

Example2:

#include<stdio.h>
#include<conio.h>

void swap(int a, int b)


{
int temp;
temp=a;
a=b;
b=temp;
}

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.

Let's try to understand the concept of call by reference in


c language by the example given below:
1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&x);//passing reference in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Example2:

#include<stdio.h>
#include<conio.h>

void swap(int *a, int *b)


{
int temp;
temp=*a;
*a=*b;
*b=temp;
}

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.

To understand this guide, you should have the knowledge of following C


Programming topics:

1. C – Array
2. Function call by value in C
3. Function call by reference in C

Passing array to function using call by value method


As we already know in this type of function call, the actual parameter is copied to
the formal parameters.

#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:

Value of var_arr[0] is: 11


Value of var_arr[1] is: 22
Value of var_arr[2] is: 33
Value of var_arr[3] is: 44
Value of var_arr[4] is: 55
Value of var_arr[5] is: 66
Value of var_arr[6] is: 77

What does main( ) Return?

 The main() function returns an integer to calling process, which


generally the operating system.
 Returning a value from main() is the equvivalent of calling exit()
With the same value.
 If main() does not explicitly return a value, the value passed to the
calling process is technically undefined.
 If main( ) does not explicitly return a value the value passed to the
calling process is technically undefined.
 In practice most C compilers automatically return 0,but do not rely
on this if portability is a concern.

Potrebbero piacerti anche