When you are learning how to learn C++ step by step, you eventually reach a point where you expect arrays to behave just like the variables you’ve already mastered. You might think, “If I can add two integers with a + b, why can’t I add two arrays with arr1 + arr2?”
The truth is, arrays have a very specific set of “rules” or exceptions. Unlike normal variables, you cannot perform operations on an array “as a whole.” In this guide, we will look at exactly how operations like assignment, summation, and output differ when dealing with arrays.
Exceptions Between Normal Variable and Array
Here are the few exceptions or the differences between the basic operations on a simple variable and on an array.
1. The Assignment Exception: You Can’t Just Copy-Paste
With a normal variable, if you have
int a = 5; and int b;, you can simply write b = a;. Now b is also 5.The Array Difference: You cannot assign one array directly to another. If you have
int arr1[size]and int arr2[size], writing arr1 = arr2; is the wrong way and will result in a compiler error.2. The Summation Exception: No “Bulk” Math
For normal variables,
sum = a + b; works perfectly.The Array Difference: If you try to write
total = arr1 + arr2;, C++ will not understand that you want to add the contents of the boxes together.3. The Output Exception: Printing the “Row,” Not the “Label”
If you have
int a = 10;, you can simply write cout << a; to see “10” on your screen.The Array Difference: You cannot write
cout << arr; to see all the numbers inside the array. Doing this is “wrong” and won’t give you the values you expect.Relatable Daily Life Example: The Tray of Water Glasses
Imagine a Normal Variable is a single glass of water. If you want to move the water, you just pick up the glass and move it. Simple!
Now, imagine an Array is a tray containing 10 glasses of water.
- Assignment/Sum: If you want to “pour” the water from one tray into another, you can’t just tilt the whole tray and expect it to work perfectly. You have to pick up each glass one-by-one and pour it into the corresponding glass on the other tray.
In C++, the Loop is your hand that picks up each glass one-by-one.
