Site icon Teaching Newbies since 2014

C++ functions

A function may contain 1 or more statements of code. When a function is called, the statements of code within a function block are executed.

Syntax:


returnValue function_name(parameters){
statements of code
}
When a function need not return anything, we use the “void” return type:
void function_name(parameters){
statements of code
}
Example:
#include <iostream>
#include <string>
using namespace std;

void printString(string a, string b){
  cout << a << "\n";
  cout << b << "\n";
}
int main(){
  string s1 = "Love";
  string s2 = "Nice";

  printString(s1, s2);
}
This is a simple function called printString that takes in 2 parameters of the string data type and prints them out. The function printString is called from within the main function called main. PrintString function takes in 2 string values that have been assigned to variables s1 and s2
Exit mobile version