#include <iostream> #include <string> using namespace std; void greet(string name = "Guest", int times = 1) { for (int i = 0; i < times; i++) { cout << "Hello, " << name << "!\n"; } } int main() { greet(); greet("Alice", 2); return 0; }
The function greet has default parameters: name = "Guest" and times = 1. When called without arguments, it prints "Hello, Guest!" once. When called with "Alice" and 2, it prints "Hello, Alice!" twice.
#include <iostream> using namespace std; void addOne(int &num) { num += 1; } int main() { int a = 5; addOne(a); cout << a << endl; return 0; }
The function addOne takes an integer reference and increments it. The original variable a is changed from 5 to 6, so the output is 6.
#include <iostream> using namespace std; void printValue(const int &val) { cout << val << endl; } int main() { int x = 10; printValue(x); return 0; }
The function printValue takes a const reference to an int and prints it. The value of x is 10, so it prints 10.
#include <iostream> using namespace std; void setZero(int *ptr) { if (ptr) { *ptr = 0; } } int main() { int a = 5; setZero(&a); cout << a << endl; return 0; }
The function setZero takes a pointer to int and sets the pointed value to 0. Since a is passed by address, its value changes to 0.
#include <iostream> using namespace std; void print(int x) { cout << "int: " << x << endl; } void print(double x) { cout << "double: " << x << endl; } int main() { print(5); print(5.0); print('5'); return 0; }
The call print(5) matches print(int). The call print(5.0) matches print(double). The call print('5') passes a char, which is promoted to int with ASCII value 53, so print(int) is called printing 53.