6
Programming in C –Call By Prof. A. Syed Mustafa, HKBK College of Engineering Program to find area of a circle using #define. #include<stdio.h> #define PI 3.1412 int main() { int radius; float area; printf("Enter the radius: "); scanf("%d", &radius); area=PI*radius*radius; printf("Area=%.2f",area); return 0; } Use of #if, #elif, #else and #endif : The preprocessor directives #if, #elif, #else and #endif allows to conditionally compile a block of code based on predefined symbols. #include<stdio.h> #define MAX 100 void main( ) { #if (MAX) printf("MAX is defined"); #else printf ("MAX is not defined"); #endif } Preprocessor Directive / Macros The C preprocessor [CPP] is a macro processor that is used automatically by the C compiler to transform programmer defined programs before actual compilation takes place. It is called a macro processor because it allows the user to define macros, which are short abbreviations for longer constructs. It instructs the compiler to do required pre-processing before the actual compilation. All preprocessor directives begin with the # symbol (known as pound or hash). List of pre-processor directives: 1. #include: This is used insert a particular header from another file. 2. #define, #undef : These are used to define and un-define conditional compilation symbols. 3. #if, #elif, #else, #endif : These are used to conditionally skip sections of source code. Example: #include “demo.h” tells CPP to get demo.h from the local directory and add the content to the current source file. #define PI 3.1412 /* defines symbolic constant */ This directive tells the CPP to replace symbolic constant pi with 3.1412. #define SIZE 5 /* SIZE will be replaced with 5 */

Pointers and call by value, reference, address in C

Embed Size (px)

Citation preview

Page 1: Pointers and call by value, reference, address in C

Programming in C –Call By

Prof. A. Syed Mustafa, HKBK College of Engineering

Program to find area of a circle using #define.

#include<stdio.h>

#define PI 3.1412

int main()

{

int radius; float area;

printf("Enter the radius: ");

scanf("%d", &radius);

area=PI*radius*radius;

printf("Area=%.2f",area);

return 0;

}

Use of #if, #elif, #else and #endif :

The preprocessor directives #if, #elif, #else and #endif allows to

conditionally compile a block of code based on predefined symbols.

#include<stdio.h>

#define MAX 100

void main( )

{

#if (MAX)

printf("MAX is defined");

#else

printf ("MAX is not defined");

#endif

}

Preprocessor Directive / Macros

The C preprocessor [CPP] is a macro processor that is used

automatically by the C compiler to transform programmer defined

programs before actual compilation takes place. It is called a macro

processor because it allows the user to define macros, which are short

abbreviations for longer constructs.

It instructs the compiler to do required pre-processing before the

actual compilation. All preprocessor directives begin with the #

symbol (known as pound or hash).

List of pre-processor directives:

1. #include: This is used insert a particular header from another file.

2. #define, #undef : These are used to define and un-define

conditional compilation symbols.

3. #if, #elif, #else, #endif : These are used to conditionally skip

sections of source code.

Example:

#include “demo.h”

tells CPP to get demo.h from the local directory and add the

content to the current source file.

#define PI 3.1412 /* defines symbolic constant */

This directive tells the CPP to replace symbolic constant pi

with 3.1412.

#define SIZE 5 /* SIZE will be replaced with 5 */

Page 2: Pointers and call by value, reference, address in C

Programming in C –Call By

Prof. A. Syed Mustafa, HKBK College of Engineering

MEMORY ALLOCATION FUNCTIONS

1. Static Memory Allocation:

Memory space allocated from stack at compile time for variables

declared in the program is fixed, it cannot be altered during

execution-time. This is called static memory allocation.

Example: int a[5]; float d;

2. Dynamic Memory Allocation

It is the process of allocating memory-space during execution-time

i.e. run time from Heap. If there is an unpredictable storage

requirement, then the dynamic allocation technique is used.

This allocation technique uses predefined functions to allocate and

release memory for data during execution-time.

There are 4 library functions for dynamic memory allocation:

malloc( ), calloc( ), free( ), realloc( )

These library functions are defined under "stdlib.h"

1. malloc( ) -memory allocation

This function is used to allocate the required memory-space

during execution-time.

The syntax is shown below:

data_type *p;

p=(data_type*)malloc(size);

Here p is pointer variable.

data_type can be int, float or char. size is number of bytes to be

allocated.If memory is successfully allocated, then address of the first

byte of allocated space is returned. If memory allocation fails, then

NULL is returned.

For ex: int *ptr;

ptr=(int*)malloc(100*sizeof(int));

The above code will allocate 200 bytes assuming sizeof(int)=2 bytes.

2. calloc( ) - contiguous allocation This function is used to allocate the required memory-size during

execution-time and at the same time, automatically initialize

memory with 0's.

syntax :

data_type *p;

p=(data_type*)calloc(n,size);

Ex:

p=(int*)calloc(25,sizeof(int));

3. free( )

Dynamically allocated memory with either calloc( ) or malloc( ) can

be deallocated using free( ) explicitly to release space.

syntax:

free(ptr);

4. realloc() -reallocation

If the previously allocated memory is insufficient or more than

sufficient. Then, we can change memory-size previously allocated

using realloc().

The syntax is shown below:

ptr=(data_type*)realloc(ptr,newsize);

void main( )

{ int i;

int *a= (int *)malloc(10);

for(i=0;i<5;i++)

*(a+i)=i+10;

for(i=0;i<5;i++)

printf(“%d\t”,*(a+i)10;

}

Output: 10 11 12 13 14

Page 3: Pointers and call by value, reference, address in C

Programming in C –Call By

Prof. A. Syed Mustafa, HKBK College of Engineering

Pointers

A Pointer is just an address of the data stored in memory.

A pointer is a variable whose value is the address of

another variable, i.e., direct address of the memory

location.

Syntax: <variable_type> *<name>=&variable; eg:- int *a=&b;

‘*’ used to declare a pointer variable and also used to retrieve the value from the pointed memory location. ‘*’ is also called as derefence operator. #include <stdio.h> void main () { int a = 20; /* actual variable declaration */ int *ip; /* pointer variable declaration */

ip = &a; /* store address of var in pointer variable*/

printf("Address of variable a is: %x\n", &a );

/* address stored in pointer variable */

printf("Address stored in variable ip is: %x\n", ip );

/* access the value using the pointer */

printf("Value of *ip variable: %d\n", *ip );

}

Output: Address of variable a is: bffd8b3c Address stored in variable ip is: bffd8b3c Value of *ip variable: 20

Actual Parameter

The parameter’s value (or arguments) we provide while calling

a function is known as actual arguments.

Parameter Written In Function Call is Called “Actual Parameter”

Actual parameters are parameters as they appear in function calls.

The actual value that is passed into the function by a caller.

Formal Parameter

Formal parameters are parameters as they appear in function

declarations.

the identifier used in a method to stand for the value that is passed

into the function by a caller.

Parameter Written In Function Definition is Called “Formal Parameter”

While declaring a function, the arguments list of parameters we

specify are known as formal parameters.

Example

Page 4: Pointers and call by value, reference, address in C

Programming in C –Call By

Prof. A. Syed Mustafa, HKBK College of Engineering

CALL BY ADDRESS

The call to the function passes variable’s

address to the called function. The actual

arguments are not copied to the formal

arguments, the addresses of actual

arguments (or parameters) are passed to

the formal parameters. Hence any

operation performed by function on

formal arguments / parameters affects

actual parameters.

void swap(int *x, int *y)

{ int t=*x; *x=*y; *y=t;

}

void main( ) {

int a=5, b=10 ;

printf("Before swap: a=%d,b=%d",a,b);

swap(&a,&b); /*calling swap function*/

printf("After swap: a= %d,b=%d",a,b);

} Output: Before swap: a=5,b=10 After swap: a=10,b=5 Because variable declared ‘a’, ‘b’ in main() is different from variable ‘x’, ’y’ in swap(). Only variable names are different but both a and x, b and y point to the same memory address locations respectively.

CALL BY REFERENCE

The call to the function passes base address to

the called function. The actual arguments are

not copied to the formal arguments, only

referencing is made. Hence any operation

performed by function on formal arguments /

parameters affects actual parameters.

void change(int b[ ])

{

b[0]=10; b[1]=20; b[2]=30;

}

void main( )

{

int a[3]={ 5, 15, 25 } ;

printf("BeforeChange:%d,%d,%d",a[0],a[1],a[2]);

change(a); /*calling swap function*/

printf("AfterChange:%d,%d,%d",a[0],a[1],a[2]);

}

Output: BeforeChange: 5,15,25 AfterChange: 10,20,30 Because array variable declared ‘b’ in change() is referencing/ pointing to array variable ‘a’ in main(). Only variable name is different but both are pointing / referencing to same memory address locations.

CALL BY VALUE

The call to the function passes either the values

or the normal variables to the called function.

The actual arguments are copied to the formal

arguments, hence any operation performed by

function on arguments doesn’t affect actual

parameters.

void swap(int a, int b)

{

int t=a; a=b; b=t;

}

void main( )

{

int a=5, b=10 ;

printf("Before swap: a=%d,b=%d",a,b);

swap(a,b); /*calling swap function*/

printf("After swap: a= %d,b=%d",a,b);

}

Output: Before swap: a=5,b=10 After swap: a=5,b=10 Because variable declared ‘a’, ‘b’ in main() is different from variable ‘a’, ’b’ in swap(). Only variable names are similar but their memory address are different and stored in different memory locations.

Page 5: Pointers and call by value, reference, address in C

Programming in C –Call By

Prof. A. Syed Mustafa, HKBK College of Engineering

STACKS

• A stack is a special type of data structure where elements are inserted from one end and elements are deleted from the same end.

• Using this approach, the Last element Inserted is the First element to be deleted Out, and hence, stack is also called LIFO data structure.

• The various operations performed on stack:

Insert: An element is inserted from top end. Insertion operation is called push operation. Delete: An element is deleted from top end. Deletion operation is called pop operation. Overflow: Check whether the stack is full or not.

Underflow: Check whether the stack is empty or not.

• This can be pictorially represented as shown below:

APPLICATIONS OF STACK

1) Conversion of expressions: The compiler converts the infix expressions into postfix expressions using stack.

2) Evaluation of expression: An arithmetic expression represented in the form of either postfix or prefix can be easily evaluated using stack.

3) Recursion: A function which calls itself is called recursive function.

4) Other applications: To find whether the string is a palindrome, to check whether a given expression is valid or not.

Page 6: Pointers and call by value, reference, address in C

Programming in C –Call By

Prof. A. Syed Mustafa, HKBK College of Engineering

PRIMITIVE AND NON-PRIMITIVE DATA TYPES

Data type specifies the type of data stored in a variable. The data type can be classified into two types: 1) Primitive data type and 2)Non-Primitive data type

Primitive Data Type

• The primitive data types are the basic data types that are available in most of the programming

languages.

• The primitive data types are used to represent single values.

Integer: This is used to represent a number without decimal point. Eg: int a=12;

Float: This is used to represent a number with decimal point. Eg: float a=45.1; double b=67.3;

Character: This is used to represent single character Eg: char ch=‘C’; char ch1= ‘a’;

Non Primitive Data Type

• The data types that are derived from primary data types are known as non-Primitive data types.

• These datatypes are used to store group of values. • The non-primitive data types are

Arrays, Structure

Stacks, Linked list

Queue, Binary tree