C++ Function Definition

Introduction

To be called in a program, a function must be defined first.

A function definition has everything a function declaration has, plus the body of a function.

Those are a return type, a function name, a list of function parameters, if any, and a function body.

Example:

#include <iostream> 

void myfunction(); // function declaration 

int main() //from  www.j a  v a2s  .  c  o m
{ 

} 

// function definition 
void myfunction() { 
    std::cout << "Hello World from a function."; 
} 

To define a function that accepts one parameter, we can write:

int mysquarednumber(int x); // function declaration 

int main() //from w  ww.  jav a2 s .  c  o m
{ 

} 

// function definition 
int mysquarednumber(int x) { 
    return x * x; 
} 

To define a function that accepts two parameters, we can write:

int mysquarednumber(int x); // function declaration 

int main() /*from  www .  ja va 2  s  .c  o m*/
{ 

} 

// function definition 
int mysquarednumber(int x) { 
    return x * x; 
} 



PreviousNext

Related