Tuesday, 18 June 2019

C++ Pointers and References: Quick Reference

After watching a few hours of an Intro to C++ series on Pluralsight, this is a succinct aide-memoir for myself for C++ pointers and references.

#include <iostream>
int main() {
int ten = 10;
int fifty = 50;
int* pointer; // pointers can be null
pointer = &ten; // they hold memory addresses (&ten = the memory address of variable 'ten')
pointer = &fifty; // and pointers can be reassigned
std::cout << pointer << "\n"; // this writes the address pointer holds
std::cout << *pointer << "\n"; // this writes out the value of the address pointer is pointing to
int& reference = ten; // references are non-null, assigned-once aliases for other variables
std::cout << reference; // this is the same as std:cout << ten
}
// Output:
// 0xfff000bcc
// 50
// 10

No comments:

Post a Comment