From 869e68986aa8f69af6e7842260a68d1e5c6f796f Mon Sep 17 00:00:00 2001 From: Carlos Maiolino Date: Thu, 10 Jul 2025 22:24:20 +0200 Subject: Add a bunch of code Signed-off-by: Carlos Maiolino --- CPP/Basics/functions.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 CPP/Basics/functions.cpp (limited to 'CPP/Basics/functions.cpp') diff --git a/CPP/Basics/functions.cpp b/CPP/Basics/functions.cpp new file mode 100644 index 0000000..5a26992 --- /dev/null +++ b/CPP/Basics/functions.cpp @@ -0,0 +1,41 @@ +#include + +// C++ can pass arguments are references + +// by value +int square(int x) +{ + return x * x; +} + +// swap by value (passing pointers) +void swap(int *x, int *y) +{ + int temp = *x; + *x = *y; + *y = temp; +} + +// Swap by reference - function overload +void swap(int& x, int& y) +{ + int temp = x; + x = y; + y = temp; +} + + +int main(void) { + + int a = 9, b; + b = square(a); + std::cout << "Square of a: " << b << std::endl; + std::cout << "A: " << a << " B: " << b << std::endl; + swap(&a, &b); + std::cout << "Swapping by addr value:" << std::endl; + std::cout << "New A: " << a << " New B: " << b << std::endl; + swap(a, b); + std::cout << "Swapping by reference:" << std::endl; + std::cout << "New A: " << a << " New B: " << b << std::endl; + return 0; +} -- cgit v1.2.3