Tech Study

Functions in C++

Introduction :

Functions in C++

A block of code which comes into execution when it is called is a function.

We can pass data to the function which are called as parameters.

Functions are known for performing certain actions, and they play a significant role in code reusanility: You can define the code once, and then use it many times.

Creating a functions in c++

Syntax:

void rishFunc () {
  // code piece  that we want to be executed
}

Example Explanation:

  • rishFunc() is the name of the function
  • void specific’s that the function does not have a return value. 
  • inside the function, we are supposed to add code that defines what the function should do

Calling a Function:

Functions are not executed immediately after being declared. They are actually saved for later use, and when they will be called they will get executed.

We have to write the function’s name followed by two parentheses () and a semicolon to call a function;

Following is an example, rishFunc () is used to print any text , when it is called:

For Example:

// Creating the function
void rishFunc () {
  cout << "Hey There! I’m Rishu!";
}

int main() {
  rishFunc (); 
  return 0;
}

Outputs: “Hey There! I’m Rishu”

Declaration and Definition of a function:

A functions in c++ generally consists of two parts:

  • Declaration: It is supposed to consist the return type, the name of the function, and parameters (if present)
  • Definition: It is considered to be the body of the function (the desired code to be executed)
void rishFunc () // declaration
  // the body of the function (definition)
}

Note: , An error will occur if a user-defined function, such as rishFunc () is declared after the main() function

Example:

int main() {
  rishFunc ();
  return 0;
}

void rishFunc () {
  cout << "Hey there! I’m Rishu”;
}

However, it can be possible for someone to separate the declaration and the definition of the function – for the sake of code optimization.

One can often see C++ programs that generally have function declarations above main(), and function definition is generally found below main(). This is supposed to make the code better organized and easier to read:

For example:

// Declaring the function
void rishFunc ();

// The main method
int main() {
  rishFunc ();  // calling the function
  return 0;
}

// Function definition
void myFunction() {

 cout << "Hey there! I’m Rishu”;
}

functions in c++

Python Examples

Introduction: Python Examples are the basic programming concepts of python like python syntax,python data types,,python operators,python if else,python comments etc.. …

Read more

C String Functions

C String Functions perform certain operations, It provides many useful string functions which can come into action. The <string.h> header …

Read more