Magic Boxes, Functions
In C++, you can bundle common code and give it a name. This is called a function.
Create a function
When you define a function, you must clearly specify the input and output types.
// 1. Greeting function (returns nothing -> void)
void sayHello() {
std::cout << "Hello!" << std::endl;
}
// 2. Add function (returns a number)
int add(int a, int b) {
return a + b;
}
int main() {
sayHello(); // use it
int result = add(10, 20);
std::cout << "Result: " << result << std::endl;
return 0;
}
Translation:
Define a magic box called add:
(output is an int)
(inputs are numbers a and b)
{
return a + b
}
Why so strict?
In C++, if you declare “this function takes ints and returns an int,” the language enforces it. That reduces the chance of crashes or weird values.
This precision is where C++ strength begins.