In C++, you can use references to pass variables to functions. This way, the function can modify the original variables directly.
void swapNumbers(int &a, int &b) { int temp = a; a = b; b = temp; } int main() { int x = 10; int y = 20; swapNumbers(x, y); std::cout << "x is " << x << "\n"; std::cout << "y is " << y << "\n"; }
A `const` reference means the function can use the variable but cannot change it. This is useful for passing large objects without copying them.
int multiplyByThree(const int num) { return num * 3; }
Pointers store memory addresses of variables. This allows you to directly access and modify the variable's value.
int value = 42; int* ptr = &value; // ptr now holds the address of value
A reference is an alias for another variable. It allows you to use a different name to access the same variable.
int original = 5; int &alias = original; // alias is another name for original
A pointer variable holds the memory address of another variable. You use the `&` operator to get a variable's address and `*` to access the value at that address.
int count = 10; std::cout << &count << "\n"; // Prints the memory address of count std::cout << *(&count) << "\n"; // Dereferences the pointer to print the value at that address (10)
Dereferencing a pointer means accessing the value at the address stored by the pointer. This is done using the `*` operator.
int number = 7; int* ptr = &number; int value = *ptr; // value is now 7, the content of number
Welcome to our comprehensive collection of programming language cheatsheets! Whether you're a seasoned developer or a beginner, these quick reference guides provide essential tips and key information for all major languages. They focus on core concepts, commands, and functions—designed to enhance your efficiency and productivity.
ManageEngine Site24x7, a leading IT monitoring and observability platform, is committed to equipping developers and IT professionals with the tools and insights needed to excel in their fields.
Monitor your IT infrastructure effortlessly with Site24x7 and get comprehensive insights and ensure smooth operations with 24/7 monitoring.
Sign up now!