Functions and Strings

Functions

Syntax

//the first type is the type of the return value (or return type)
TYPE functionName(TYPE name, TYPE name, ..., TYPE name) { //the values in brackets are the parameters (arguments)
    statement;
    statement;
    statement;
    statement;
    ...
    statement;
    return expression; //if return type is not void
}

Calling a function:

functionName(value, value, ..., value);  //the values in brackets are the parameters (arguments)

Defining a function

#include "console.h"
using namespace std;
const string CLASS_NAME = "COL100";

//Function definition and code
void lectures(int count)
{
  cout << count << " lectures of " << CLASS_NAME << " are remaining." << endl;
  cout << "One lecture just got finished. " << (count - 1) << " lectures of " << CLASS_NAME << " remaining." << endl << endl;
}

int main() {
  for (int i = 28; i > 0; i--) {
    lectures(i);
  }
  return 0;
}

Declaration order

If we reverse the declaration order (i.e., first main, then lectures):
#include "console.h"
using namespace std;
const string CLASS_NAME = "COL100";

int main() {
  for (int i = 28; i > 0; i--) {
    lectures(i);
  }
  return 0;
}


//Function definition and code
void lectures(int count)
{
  cout << count << " lectures of " << CLASS_NAME << " are remaining." << endl;
  cout << "One lecture just got finished. " << (count - 1) << " lectures of " << CLASS_NAME << " remaining." << endl << endl;
}

Function prototypes

TYPE functionName(TYPE name, TYPE name, ..., TYPE name) { //the values in brackets are the parameters (arguments);
#include "console.h"
using namespace std;
const string CLASS_NAME = "COL100";

void lectures(int count);

int main() {
  for (int i = 28; i > 0; i--) {
    lectures(i);
  }
  return 0;
}


//Function definition and code
void lectures(int count)
{
  cout << count << " lectures of " << CLASS_NAME << " are remaining." << endl;
  cout << "One lecture just got finished. " << (count - 1) << " lectures of " << CLASS_NAME << " remaining." << endl << endl;
}

Pass by value

void swap(int a, int b) {
  int temp = a;
  a = b;
  b = temp;
}

int main() {
  int x = 17;
  int y = 35;
  swap(x, y);
  cout << x << ", " << y << endl;  //17, 35
  return 0;
}

Pass by Reference

If you declare a parameter with an & after its type, it will link the caller and callee functions to the same place in memory:
void swap(int &a, int &b)
{
  int tmp = a;
  a = b;
  b = tmp;
}

int main() {
  int x = 17;
  int y = 35;
  swap(x, y);
  cout << x << ", " << y << endl;  //35, 17
  return 0;
}