Skip to content

Function, Reference, and Struct

Function:

In C++, we can define some functions ourself with a return type and parameters(or no parameters).

let's focus on the function's declaration:int sum(int a, int b)

'int' indicates that the return type of the function is an integer. (int a, int b)tells us that there are two parametersa and bwith the type of int

1
2
3
4
5
6
7
8
9
#include <iostream>
int sum(int a, int b){
    return a + b;
}
int main(){
    int a, b;
    cin >> a >> b;
    cout << sum(a, b) << endl;
}

Functions can also have many kinds of return type

such as bool, void, doubleand so on.

Using the return type bool, we can write some conditioning function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <iostream>
bool equal(int a, int b){
    return a == b;
}
int main(){
    int a, b;
    cin >> a >> b;
    if(equal(a, b)) cout << "is equal" << endl;
    return 0;
}

Reference

In previous examples, if we modify the formal parameter inside function, the actual parameter outside the function are not modified.

Thus, if we want to modify the actual parameter(the real parameter we use when calling the function) inside the function, we can use & to make a reference.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <iostream>
using namespace std;
void plus_one(int &a){  // increase a by 1
    a++;
}
int main(){
    int a;
    cin >> a;
    plus_one(a);
    cout << a << endl;
}

Struct

When we want to store multiple data in one variable, we can create a struct to achieve this goal.

In a struct, we can have multiple variables and even functions built in it, but we don't often do it in competitive programming.(from my personal perspective)

After declaring this struct, we can use it as a variable type and declare variables using struct's name:point p1; just like how we define an integerint p2;

1
2
3
4
5
6
7
8
9
#include <iostream>
struct point{
    int x, y;
}
int main(){
    point p1;
    p1.x = 10;
    p1.y = 15;
}

Struct may not seem powerful at first, but it is useful when we are dealing with situations that each single element has multiple attributes.(such as some graph algorithms)

Practice Problems:

to be completed.