0% found this document useful (0 votes)
2 views

C Function

The document provides an overview of functions in C programming, detailing their benefits, types (built-in and user-defined), and how to declare, define, and call them. It also explains concepts like call by value and call by reference, variable scopes (local and global), recursion, storage classes, and preprocessor directives. Additionally, it includes examples of various C programs demonstrating these concepts.

Uploaded by

jojiba2617
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C Function

The document provides an overview of functions in C programming, detailing their benefits, types (built-in and user-defined), and how to declare, define, and call them. It also explains concepts like call by value and call by reference, variable scopes (local and global), recursion, storage classes, and preprocessor directives. Additionally, it includes examples of various C programs demonstrating these concepts.

Uploaded by

jojiba2617
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

C function is a self-contained block of statements that can be executed repeatedly whenever we

need it.

Benefits of using the function in C


 The function provides modularity.
 The function provides reusable code.
 In large programs, debugging and editing tasks is easy with the use of functions.
 The program can be modularized into smaller parts.
 Separate function independently can be developed according to the needs.

There are two types of functions in C


 Built-in(Library) Functions
o The system provided these functions and stored in the library. Therefore it is also
called Library Functions.
e.g. scanf(), printf(), strcpy, strlwr, strcmp, strlen, strcat etc.
o To use these functions, you just need to include the appropriate C header files.
 User Defined Functions These functions are defined by the user at the time of writing the
program.

Parts of Function
1. Function Prototype (function declaration)
2. Function Definition
3. Function Call

1. Function Prototype
Syntax:
dataType functionName (Parameter List)

Example:
int addition();

2. Function Definition
Syntax:
returnType functionName(Function arguments){

//body of the function

}
Example:
int addition()

3. Calling a function in C

Program to illustrate the Addition of Two Numbers using User Defined


Function
Example:
#include<stdio.h>

/* function declaration */int addition();

int main()

/* local variable definition */ int answer;

/* calling a function to get addition value */ answer = addition();

printf("The addition of the two numbers is: %d\n",answer);

return 0;

/* function returning the addition of two numbers */int addition()

/* local variable definition */ int num1 = 10, num2 = 5;

return num1+num2;

Program Output:
The addition of the two numbers is: 15
While calling a function, the arguments can be passed to a function in two ways, Call by value and call by reference.
Type Description

Call by Value  The actual parameter is passed to a function.


 New memory area created for the passed parameters, can be used only within the
function.
 The actual parameters cannot be modified here.
Call by Reference  Instead of copying variable; an address is passed to function as parameters.
 Address operator(&) is used in the parameter of the called function.
 Changes in function reflect the change of the original variables.
Table of Contents
# Call by Value
# Call by Reference

Call by Value
Example:
#include<stdio.h>

/* function declaration */int addition(int num1, int num2);

int main()

/* local variable definition */ int answer;

int num1 = 10;

int num2 = 5;

/* calling a function to get addition value */ answer = addition(num1,num2);

printf("The addition of two numbers is: %d\n",answer);

return 0;

/* function returning the addition of two numbers */int addition(int a,int b)


{

return a + b;

Program Output:
The addition of two numbers is: 15

Call by Reference
Example:
#include<stdio.h>

/* function declaration */int addition(int *num1, int *num2);

int main()

/* local variable definition */ int answer;

int num1 = 10;

int num2 = 5;

/* calling a function to get addition value */ answer = addition(&num1,&num2);

printf("The addition of two numbers is: %d\n",answer);

return 0;

/* function returning the addition of two numbers */int addition(int *a,int *b)

return *a + *b;

Program Output:
The addition of two numbers is: 15
The C library functions are provided by the system and stored in the library. The C library function is also called an

inbuilt function in C programming.


To use Inbuilt
definitions of the
Function
function.
in C, you must include their respective header files, which contain prototypes and data

C Program to Demonstrate the Use of Library Functions


Example:
#include<stdio.h>

#include<ctype.h>

#include<math.h>

void main()

int i = -10, e = 2, d = 10; /* Variables Defining and Assign values */ float rad =
1.43;

double d1 = 3.0, d2 = 4.0;

printf("%d\n", abs(i));

printf("%f\n", sin(rad));

printf("%f\n", cos(rad));

printf("%f\n", exp(e));

printf("%d\n", log(d));

printf("%f\n", pow(d1, d2));

Program Output:
A scope is a region of the program, and the scope of variables refers to the area of the program
where the variables can be accessed after its declaration.
In
where
that
In C
Cregion.
every
a variable
variable
programming, hasdefined
its existence;
variable in scope.
moreover,
declared You canathat
within define
variable
scope
function cannot
as the be
is differentsection
useda or
from or region
accessed
variable of beyond
a program
declared
outside of a function. The variable can be declared in three places. These are:
Position Type

Inside a function or a block. local variables

Out of all functions. Global variables

In the function parameters. Formal parameters

So, now let's have a look at each of them individually.


Local Variables
Variables that are declared within the function block and can be used only within the function is
called local variables.

Local Scope or Block Scope


A local scope or block is collective program statements put in and declared within a function or
block (a specific region enclosed with curly braces) and variables lying inside such blocks are
termed as local variables. All these locally scoped statements are written and enclosed within left
({) and right braces (}) curly braces. There's a provision for nested blocks also in C which means
there can be a block or a function within another block or function. So it can be said that
variable(s) that are declared within a block can be accessed within that specific block and all
other inner blocks of that block, but those variables cannot be accessed outside the block.
Example:
#include <stdio.h>

int main ()

/* local variable definition and initialization */ int x,y,z;

/* actual initialization */ x = 20;

y = 30;

z = x + y;
printf ("value of x = %d, y = %d and z = %d\n", x, y, z);

return 0;

Global Variables
Variables
called global
thatvariables.
are declared outside of a function block and can be accessed inside the function is
Global Scope
Global variables are defined outside a function or any specific block, in most of the case, on the
top of the C program. These variables hold their values all through the end of the program and
are accessible within any of the functions defined in your program.
Any function can access variables defined within the global scope, i.e., its availability stays for
the entire program after being declared.
Example:
#include <stdio.h>

/* global variable definition */int z;

int main ()

/* local variable definition and initialization */ int x,y;

/* actual initialization */ x = 20;

y = 30;

z = x + y;

printf ("value of x = %d, y = %d and z = %d\n", x, y, z);

return 0;

}
Global Variable Initialization
After defining a local variable, the system or the compiler won't be initializing any value to it.
You have to initialize it by yourself. It is considered good programming practice to initialize
variables before using. Whereas in contrast, global variables get initialized automatically by the
compiler as and when defined. Here's how based on datatype; global variables are defined.
datatype Initial Default Value

int 0

char '\0'

float 0

double 0

pointer NULL

C is a powerful programming language having capabilities like an iteration of a set of statements 'n' number of times.

The same concepts can be done using functions also. In this chapter, you will be learning about recursion concept

and how it can be used in the C program.


Table of Contents
# What is Recursion
# Factorial Program
# Fibonacci Program

What is Recursion
can beand
Recursion
again
programtermed
lets
again,
canyou
be
asand
call
recursion,
defined
that
the process
specific
asand
the the
technique
function
continues
function
from
oftill
inreplicating
specific
inside
which makes
that
condition
orfunction,
doing
thisreaches.
possible
again
thenan
this
In
isactivity
called
the
concept
world
inrecursive
aofof
self-similar
calling
programming,
function.
theway
function
calling
whenfrom
your
itself
itself
Here's an example of how recursion works in a program:
Example Syntax:
void rec_prog(void) {

rec_prog(); /* function calls itself */}

int main(void) {

rec_prog();

return 0;

C program
this
function,
recursion
or allows
else
concept,
it you
will continue
toyou
dohave
such
toto
calling
anbeinfinite
cautious
of function
loop,
in so
defining
within
makeanother
an
sure
exit
that
or
function,
the
terminating
condition
i.e., recursion.
condition
is set within
from
But your
when
this program.
recursive
you implement

Factorial Program
Example:
#include<stdio.h>

#include<conio.h>

int fact(int f) {

if (f & lt; = 1) {

printf("Calculated Factorial");

return 1;

return f * fact(f - 1);

int main(void) {

int f = 12;

clrscr();

printf("The factorial of %d is %d \n", f, fact(f));

getch();

return 0;

Fibonacci Program
Example:
#include<stdio.h>

#include<conio.h>

int fibo(int g) {

if (g == 0) {

return 0;

}
if (g == 1) {

return 1;

return fibo(g - 1) + fibo(g - 2);

int main(void) {

int g;

clrscr();

for (g = 0; g & lt; 10; g++) {

printf("\nNumbers are: %d \t ", fibonacci(g));

getch();

return 0;

Storage Classes are associated with variables for describing the features of any variable or
function in the C program. These storage classes deal with features such as scope, lifetime and
visibility which helps programmers to define a particular variable during the program's runtime.
These storage classes are preceded by the data type which they had to modify.
There are four storage classes types in C:

 auto
 register
 static
 extern

auto Storage Class


Syntax:
auto comes
define this storage
by default
classwith
explicitly
all local variables as its storage class. The keyword auto is used to
int roll; // contains auto by default

is the same as:


auto int roll; // in addition, we can use auto keyword

The above
only be implemented
example has
with
a variable
the localname
variables.
roll with auto as a storage class. This storage class can
register Storage Class
This storage class is implemented for classifying local variables whose value needs to be saved
in a register in place of RAM (Random Access Memory). This is implemented when you want
your variable the maximum size equivalent to the size of the register. It uses the
keyword register.
Syntax:
register int counter;

Register variables are used when implementing looping in counter variables to make program
execution fast. Register variables work faster than variables stored in RAM (primary memory).
Example:
for(register int counter=0; counter<=9; counter++)

// loop body

static storage class


Example:
This
language.
Static
On
default
is static.
the
storage
storage
other
value
Static
class
hand,
assigned
class
variables
uses
global
hasisstatic
its'0'static
preserve
scope
byvariables
the
variables
local
Cthe
compiler.
to
that
value
the
can
are
function
of
beused
The
aaccessed
variable
keyword
popularly
in which
in
even
any
used
for
itwhen
part
iswriting
todefined.
define
of
theyour
scope
programs
this
program.
limit
storage
inexceeds.
CThe
class
static int var = 6;

extern Storage class


The extern storage class is used to feature a variable to be used from within different blocks of
the same program. Mainly, a value is set to that variable which is in a different block or function
and can be overwritten or altered from within another block as well. Hence it can be said that an
extern variable is a global variable which is assigned with a value that can be accessed and used
within the entire program. Moreover, a global variable can be explicitly made an extern variable
by implementing the keyword 'extern' preceded the variable name.
Here are some examples of extern:
Example:
#include <stdio.h>

int val;

extern void funcExtern();


main()

val = 10;

funcExtern();

Another example:
Example:
#include <stdio.h>

extern int val; // now the variable val can be accessed and used from anywhere

// within the program

void funcExtern()

printf("Value is: %d\n", val);

The preprocessor is a program invoked by the compiler that modifies the source code before the
actual composition takes place.
To use any preprocessor directives, first, we have to prefix them with pound symbol #.
The following section lists all preprocessor directives:
Category Directive Description

Macro substitution #include File include


division
#define Macro define, Macro undefined
#undif

#ifdef If macro defined, If macro not defined


#ifndef

File inclusion division #if If, Else, ifElse, End if


#elif
#else
#endif

Compiler control division #line Set line number, Abort compilation, Set compiler option
#error
#pragma

C Preprocessors Examples
Syntax:
#include <stdio.h>

/* #define macro_name character_sequence */

#define LIMIT 10

int main()

int counter;

for(counter =1; counter <=LIMIT; counter++)

printf("%d\n",counter);

return 0;

In the above
#include example for loop will run ten times.
<stdio.h>

#include "header.h"

#include <stdio.h> tell the compiler to add stdio.h file from System Libraries to the current
source file, and #include "header.h" tells the compiler to get header.h from the local directory.
#undef LIMIT

#define LIMIT 20

This tells the compiler to undefine existing LIMIT and set it as 20.
#ifndef LIMIT

#define LIMIT 50

#endif

This tellsLIMIT
#ifdef the compiler to define LIMIT, only if LIMIT isn't already defined.
/* Your statements here */#endif

This tells the compiler to do the process the statements enclosed if LIMIT is defined.

C language is famous for its different libraries and the predefined functions pre-written within it. These make

programmer's effort a lot easier. In this tutorial, you will be learning about C header files and how these header files

can be included in your C program and how it works within your C language.

What are the Header Files


C compiler
Header
variables
header file
files
files
that
have
iscan
are
the
needs
helping
be
astdio.h.
'.h'
requested
toanbe
file
extension
imported
of using
your that
Cinto
the
program
contains
your
preprocessor
Cwhich
program
C function
holds
directive
with
the
declaration
the
definitions
#include.
help ofand
pre-processor
The
ofmacro
various
default
definitions.
functions
header
#include
file
and
Inthat
statement.
other
their
comes
words,
associated
All
with
the
the
the
Including a header file means that using the content of header file in your source program. A straightforward practice

while programming in C or C++ programs is that you can keep every macro, global variables, constants, and other

function prototypes in the header files. The basic syntax of using these header files is:
Syntax:
#include <file>

or
#include "file"

This kind of file inclusion is implemented for including system oriented header files. This technique (with angular

braces) searches for your file-name in the standard list of system directories or within the compiler's directory of

header files. Whereas, the second kind of header file is used for user-defined header files or other external files for

your program. This technique is used to search for the file(s) within the directory that contains the current file.

How include Works


The C's #include preprocessor directive statement exertions by going through the C preprocessors for scanning any

specific file like that of input before abiding by the rest of your existing source file. Let us take an example where you

may think of having a header file karl.h having the following statement:
Example:
char *example (void);

Example:
then, you have a main C source program which seems something like this:
#include<stdio.h>

int x;

#include "karl.h"

int main ()

printf("Program done");
return 0;

So, the compiler will see the entire C program and token stream as:
Example:
#include<stdio.h>

int x;

char * example (void);

int main ()

printf("Program done");

return 0;

Writing of Single and Multiple uses of Header files


You can use various header files based on some conditions. In case, when a header file needs to be included twice

within your program, your compiler will be going to process the contents inside it - twice which will eventually lead to

an error in your program. So to eliminate this, you have to use conditional preprocessor directives. Here's the syntax:
Syntax:
#ifndef HEADER_FILE_NAME

#define HEADER_FILE_NAME

the entire header file

#endif

Again, sometimes it's essential for selecting several diverse header files based on some requirement to be

incorporated into your program. For this also multiple conditional preprocessors can be used like this:
Syntax:
#if FIRST_SYSTEM

#include "sys.h"

#elif SEC_SYSTEM

#include "sys2.h"

#elif THRID_SYSTEM

....
#endif

You can create your custom header files in C; it helps you to manage user-defined methods, global variables, and

structures in a separate file, which can be used in different modules.

A process to Create Custom Header File in C


Example:
For example, I am calling an external function named swap in my main.c file.
#include<stdio.h>

#include"swap.h"

void main()

int a=20;

int b=30;

swap (&a,&b);

printf ("a=%d\n", a);

printf ("b=%d\n",b);

Swap method is defined in swap.h file, which is used to swap two numbers by using a temporary variable.
Example:
void swap (int* a, int* b)

int tmp;

tmp = *a;

*a = *b;

*b = tmp;

Note:
 header file name must have a .h file extension.
 In this example, I have named swap.h header file.
 Instead of writing <swap.h> use this terminology swap.h for include custom header file.
 Both files swap.h and main.c must be in the same folder.

The array is a data structure in C programming, which can store a fixed-size sequential collection
of elements of the same data type.
For
instead
example,
In the Cofprogramming
defining
if youten
want
variables.
to storean
language, tenarray
numbers,
can beit One-Dimensional,
is easier to define anTwo-
array of 10 lengths,

Dimensional, and Multidimensional.

Define an Array in C
Syntax:
type arrayName [ size ];

Example:
Thismust
size is called
be an
a one-dimensional
integer constant greater
array. An
than
array
zero.type can be any valid C data types, and array
double amount[5];

Initialize an Array in C
Arrays can be initialized at declaration time:
int age[5]={22,25,30,32,35};

Initializing each element separately in a loop:


int myArray[5];

int n = 0;

// Initializing elements of array seperately

for(n=0;n<sizeof(myArray)/sizeof(myArray[0]);n++)

myArray[n] = n;

A Pictorial Representation of the Array:

Accessing Array Elements in C


Example:
int myArray[5];

int n = 0;

// Initializing elements of array seperately

for(n=0;n<sizeof(myArray)/sizeof(myArray[0]);n++)

myArray[n] = n;

int a = myArray[3]; // Assigning 3rd element of array value to integer 'a'.

In C programming, the one-dimensional array of characters are called strings, which is terminated by a null character

'\0'.

Strings Declaration in C
Example:
There are two ways to declare a string in C programming:

Through an array of characters.


char name[6];

Through
char pointers.
*name;

Strings Initialization in C
Example:
char name[6] = {'C', 'l', 'o', 'u', 'd', '\0'};

or
char name[] = "Cloud";

Memory Representation of Above Defined String in C

Example:
#include<stdio.h>
int main ()

char name[6] = {'C', 'l', 'o', 'u', 'd', '\0'};

printf("Tutorials%s\n", name );

return 0;

Program Output:
TutorialsCloud

A pointer is a variable in C, and pointers value is the address of a memory location.


Table of Contents
# Pointer Definition in C
# Benefits of using Pointers in C
# How to use Pointers in C

Pointer Definition in C
Syntax:
type *variable_name;

Example:
int *width;

char *letter;

Benefits of using Pointers in C


 Pointers allow passing of arrays and strings to functions more efficiently.
 Pointers make it possible to return more than one value from the function.
 Pointers reduce the length and complexity of a program.
 Pointers increase the processing speed.
 Pointers save the memory.

How to use Pointers in C


Example:
#include<stdio.h>

int main ()
{

int n = 20, *pntr; /* actual and pointer variable declaration */

pntr = &n; /* store address of n in pointer variable*/

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

/* address stored in pointer variable */ printf("Address stored in pntr


variable: %x\n", pntr );

/* access the value using the pointer */ printf("Value of *pntr variable: %d\n",
*pntr );

return 0;

Address of n variable: 2cb60f04

Address stored in pntr variable: 2cb60f04

C language provides many functions that come in header files to deal with the allocation and management of

memories. In this tutorial, you will find brief information about managing memory in your program using some

functions and their respective header files.


Table of Contents

# Management of Memory

# static memory allocations

# dynamic memory allocations

Management of Memory
writing codes.
Almost
precise
program).
all
memory
Therefore,
computer
space
languages
managing
along with
can
memory
the
handle
program
utmost
system
itself,
care
memory.
which
is oneneeds
of
Allthe
thesome
major
variables
memory
tasksused
a programmer
forinstoring
your program
itself
must(i.e.,
keep
occupies
itsin
own
mind
a while
When a variable gets assigned in a memory in one program, that memory location cannot be used by another

variable or another program. So, C language gives us a technique of allocating memory to different variables and

programs.
There are two types used for allocating memory. These are:

static memory allocations


In the static memory allocation technique, allocation of memory is done at compilation time, and it stays the same

throughout the entire run of your program. Neither any changes will be there in the amount of memory nor any

change in the location of memory.

dynamic memory allocations


In dynamic memory allocation technique, allocation of memory is done at the time of running the program, and it also

has the facility to increase/decrease the memory quantity allocated and can also release or free the memory as and

when not required or used. Reallocation of memory can also be done when required. So, it is more advantageous,

and memory can be managed efficiently.

malloc, calloc, or realloc are the three functions used to manipulate memory. These commonly used functions are

available through the stdlib library so you must include this library to use them.
Table of Contents

# C - Dynamic memory allocation functions

# malloc function

# Example program for malloc() in C

# calloc function

# Example program for calloc() in C

# realloc function

# free function

# Example program for realloc() and free()

C - Dynamic memory allocation functions


Function Syntax

malloc() malloc (number *sizeof(int));

calloc() calloc (number, sizeof(int));

realloc() realloc (pointer_name, number * sizeof(int));

free() free (pointer_name);

malloc function
 malloc function is used to allocate space in memory during the execution of the program.
 malloc function does not initialize the memory allocated during execution. It carries garbage value.
 malloc function returns null pointer if it couldn't able to allocate requested amount of memory.

Example program for malloc() in C


Example:

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

int main()

char *mem_alloc;

/* memory allocated dynamically */mem_alloc = malloc( 15 * sizeof(char) );

if(mem_alloc== NULL )

printf("Couldn't able to allocate requested memory\n");

else

strcpy( mem_alloc,"google.in");

printf("Dynamically allocated memory content : %s\n", mem_alloc );

free(mem_alloc);

Program Output:

Dynamically allocated memory content : google.in


calloc function
 calloc () function and malloc () function is similar. But calloc () allocates memory for zero-initializes. However, malloc
() does not.

Example program for calloc() in C


Example:

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

int main()

char *mem_alloc;

/* memory allocated dynamically */mem_alloc = calloc( 15, sizeof(char) );

if( mem_alloc== NULL )

printf("Couldn't able to allocate requested memory\n");

else

strcpy( mem_alloc,"google.in");

printf("Dynamically allocated memory content : %s\n", mem_alloc );

free(mem_alloc);

Program Output:

Dynamically allocated memory content : google.in


realloc function
 realloc function modifies the allocated memory size by malloc and calloc functions to new size.
 If enough space doesn't exist in the memory of current block to extend, a new block is allocated for the full size of
reallocation, then copies the existing data to the new block and then frees the old block.

free function
 free function frees the allocated memory by malloc (), calloc (), realloc () functions.

Example program for realloc() and free()


Example:

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

int main()

char *mem_alloc;

/* memory allocated dynamically */mem_alloc = malloc( 20 * sizeof(char) );

if( mem_alloc == NULL )

printf("Couldn't able to allocate requested memory\n");

else

strcpy( mem_alloc,"google.in");

printf("Dynamically allocated memory content : " \ "%s\n", mem_alloc );

mem_alloc=realloc(mem_alloc,100*sizeof(char));
if( mem_alloc == NULL )

printf("Couldn't able to allocate requested memory\n");

else

strcpy( mem_alloc,"space is extended upto 100 characters");

printf("Resized memory : %s\n", mem_alloc );

free(mem_alloc);

Program Output:

Dynamically allocated memory content : google.in

Resized memory: space is extended up to 100 characters


The structure is a user-defined data type in C, which is used to store a collection of different kinds of data.

 The structure is something similar to an array; the only difference is array is used to store the same data types.
 struct keyword is used to declare the structure in C.
 Variables inside the structure are called members of the structure.
Table of Contents
# Defining a Structure in C

# Accessing Structure Members in C

Defining a Structure in C
Syntax:

struct structureName

//member definitions

};

Example:
struct Courses

char WebSite[50];

char Subject[50];

int Price;

};

Accessing Structure Members in C


Example:

#include<stdio.h>

#include<string.h>

struct Courses

char WebSite[50];

char Subject[50];

int Price;

};

void main( )

struct Courses C;

//Initialization

strcpy( C.WebSite, "google.in");

strcpy( C.Subject, "The C Programming Language");

C.Price = 0;

//Print
printf( "WebSite : %s\n", C.WebSite);

printf( "Book Author : %s\n", C.Subject);

printf( "Book Price : %d\n", C.Price);

Program Output:

WebSite : google.in

Book Author: The C Programming Language

Book Price : 0

Unions are user-defined data type in C, which is used to store a collection of different kinds of data, just like a

structure. However, with unions, you can only store information in one field at any one time.

 Unions are like structures except it used less memory.


 The keyword union is used to declare the structure in C.
 Variables inside the union are called members of the union.
Table of Contents
# Defining a Union in C

# Accessing Union Members in C

Defining a Union in C
Syntax:

union unionName

//member definitions

};

Example:

union Courses

char WebSite[50];

char Subject[50];

int Price;

};
Accessing Union Members in C
Example:

#include<stdio.h>

#include<string.h>

union Courses

char WebSite[50];

char Subject[50];

int Price;

};

void main( )

union Courses C;

strcpy( C.WebSite, "google.in");

printf( "WebSite : %s\n", C.WebSite);

strcpy( C.Subject, "The C Programming Language");

printf( "Book Author : %s\n", C.Subject);

C.Price = 0;

printf( "Book Price : %d\n", C.Price);

Program Output:

WebSite : google.in

Book Author: The C Programming Language


Book Price : 0
C is such a dominant language of its time and now, that even you can name those primary data
type of your own and can create your own named data type by blending data type and its
qualifier.
Table of Contents

# The typedef keyword in C

# Various Application of typedef

# Using typedef with Pointers

The typedef keyword in C


typedef
already
defined
intricate
this typedef
Syntax: exist
data
is
fora akeyword
C
types
data
programmer
keyword
types.
in cases
is: implemented
This
to
if the
get
keyword,
names
or toto
use
typedef
of
tellwithin
datatypes
the typically
compiler
programs.
turn employed
for
outThe
assigning
to be
typical
ainlittle
association
an
format
complicated
alternative
forwith
implementing
name
or
user-to C's
typedef <existing_names_of_datatype> <alias__userGiven_name>;

Here's a sample code snippet as of how typedef command works in C:


Example:

typedef signed long slong;

slongtype.
data
your program
Example:in the
Now
statement
for
thedefining
thing
as mentioned
isany
thissigned
'slong',
above
long
which
is
variable
used
is anfor
user-defined
type
a defining
within your
identifier
a signed
C program.
qualified
can be This
implemented
long
means:
kind ofin
slong g, d;

will allow you to create two variables name 'g' and 'd' which will be of type signed long and this
quality of signed long is getting detected from the slong (typedef), which already defined the
meaning of slong in your program.

Various Application of typedef


The concept of typedef can be implemented for defining a user-defined data type with a specific
name and type. This typedef can also be used with structures of C language. Here how it looks
like:
Syntax:

typedef struct

type first_member;

type sec_member;

type thrid_member;

} nameOfType;
HerebenameOfType
can implemented
nameOfType type1,correspond
by declaring
type2; to the
a variable
definition
of this
of structure
structureallied
type. with it. Now, this nameOfType

Simple Program of structure in C with the use of typedef:


Example:

#include<stdio.h>

#include<string.h>

typedef struct professor

char p_name[50];

int p_sal;

} prof;

void main(void)

prof pf;

printf("\n Enter Professor details: \n \n");

printf("\n Enter Professor name:\t");

scanf("% s", pf.p_name);

printf("\n Enter professor salary: \t");

scanf("% d", &pf.p_sal);

printf("\n Input done ! ");

Using typedef with Pointers


typedef can be implemented for providing a pseudo name to pointer variables as well. In this
below-mentioned code snippet, you have to use the typedef, as it is advantageous for declaring
pointers.
int* a;

The binding of pointer (*) is done to the right here. With this kind of statement declaration, you
are in fact declaring an as a pointer of type int (integer).
typedef int* pntr;

pntr g, h, i;

You might also like