Tutoriel Python 3 pour débutants.
Defining a Function
#include <iostream>
using namespace std;
// returnType functionName(parameters) { body }
int add(int a, int b) {
return a + b;
}
double circleArea(double r) {
return 3.14159 * r * r;
}
int main() {
cout << add(3, 4) << endl; // 7
cout << circleArea(5.0) << endl; // 78.539...
return 0;
}
Pass by Value vs Reference
void doubleByValue(int x) { x *= 2; } // copy, original unchanged
void doubleByRef(int& x) { x *= 2; } // reference, original changes
int n = 5;
doubleByValue(n); // n still 5
doubleByRef(n); // n is now 10
Default Arguments
void greet(string name, string greeting = "Hello") {
cout << greeting << ", " << name << "!" << endl;
}
greet("Alice"); // Hello, Alice!
greet("Bob", "Hi"); // Hi, Bob!
Function Overloading
int multiply(int a, int b) { return a * b; }
double multiply(double a, double b) { return a * b; }
multiply(2, 3); // int version → 6
multiply(2.5, 3.0); // double version → 7.5
Recursion
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
// factorial(5) → 120
Inline Functions
inline int square(int x) { return x * x; }
// Compiler may expand this at the call site for performance
cout << square(4); // 16