Skip to content

Instantly share code, notes, and snippets.

@mshafae
Last active December 13, 2023 23:16
Show Gist options
  • Save mshafae/7323b58b786d7db312a39ab8b0373413 to your computer and use it in GitHub Desktop.
Save mshafae/7323b58b786d7db312a39ab8b0373413 to your computer and use it in GitHub Desktop.
Using references and C++ array.
// Gist https://gist.github.com/7323b58b786d7db312a39ab8b0373413
#include <array>
#include <iostream>
#include <string>
int main(int argc, char const* argv[]) {
std::array<int, 5> my_array{11, 12, 13, 14, 15};
// Does not change the values in the array
std::cout << "Showing the arrat contents.\n";
for (int number : my_array) {
std::cout << number << "\n";
number = 42;
}
// Show the contents of the array to prove there was no change
std::cout << "Showing the array contents and nothing has changed.\n";
for (int number : my_array) {
std::cout << number << "\n";
}
// Using a reference, change the values in the array
std::cout << "Showing the array contents and changing the values.\n";
for (int& number : my_array) {
std::cout << number << "\n";
number = 42;
}
// The values are now changed.
std::cout << "The values have all changed.\n";
for (int number : my_array) {
std::cout << number << "\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment