Functions as the name suggest “to do some task ” . Similarly  in c/c++ ,functions are group of some codes that together performs a certain task. Every C/C++ program has atleast one function i.e main() .
Code can be divided into many functions , such that each function performs a specific task .Also functions are made to reduce cost per head of making a bit program which takes lot of memory space and consumes lot of time in writing so many lines again and again . Hence its better to use functions , because here we just need to use a name in place of a whole bunch of coded lines .

SYNTAX

datatype function_name(parameters , parameters ,….)
{

statements …..;
}

EXAMPLE

void abc( )
{

. . . . . . .

}

There are two things in this :

  • function declearation
  • function defination

FUNCTION DECLEARATION
In this just name of the function is written to inform the compiler ,that a function exists , if encountered in the program , then it should not give any error . Plus it declears that a function with xyz name exits in that particular program .In good programs functions are usually decleared first and are defined later . This just looks nice 😛

SYNTAX
datatype function_name();
note:
A function declearation always  ends with a  semi colon ( ” ;”).

EXAMPLE

void abc( );

Here only the function abc ( ) is decleared , now we can define it anywhere be it inside main() or outside main() its upto the programmer .

FUNCTION DEFINITION

In this a function is defined i.e the role of the function is explained in statements written within the curly paranetheses ({ }) .

SYNTAX

datatype function_name()
{

statements ;
}

EXAMPLE

void sum( int a , int b)
{
int c;
c=a+b;
cout<<c;     //for c users printf(“%d”,c);
}

void main( )
{
int a,b;
cout<<“enter the two numbers”<<endl      //printf(“Enter the two num\n”);
cin>>a>>b;                                                               //scanf(“%d%d”,a,b);
sum(a,b); //passing the value to the function
}

Here first the function is defined . As I have told you earlier main itself is a function but its a function that we need to define in every c++ program .So, leaving it aside we defined a function sum() here with 2 parameters .These  parameters are the variables that can be entered by the  user or the programmer can insert value in them by first storing the value in a variable and then passing them in the function .

Here in our example we first asked the user for the 2 numbers and then passed them to the fuction . Clearly you can see we didnt use int ( datatype of variables passed ) , this is done because we already defined them as int so we need not define them again and again . If  datatype is used while passing the value then see errors are generated .

 

functions in c++
functions in c++

 

The rest will be discussed in next post.