The high-level distinction is object lifetime. For example, if you were writing a video game, you would allocate the objects corresponding to monsters on the heap, via new
. That way, the monster's underlying object lives exactly as long as the monster does, which is unknowable when you write the program. When the player kills the monster, your code can destroy the monster object using delete
.
A total-score counter, on the other hand, you would use the other form, because you know how long you want the counter to stay around (presumably, as long as the game is running!). By putting that form in the "global scope," outside of any function body, it would be allocated statically, as part of the program binary itself.
Finally, if you were computing the sum of an array, like this:
int mysum(int* arr, int len) {
int sum = 0;
for (int i = 0; i < len; ++i) { sum += arr[i] }
return sum;
}
the sum
variable is allocated on the stack, which is basically what you want: a temporary variable that you don't have to explicitly deallocate, and which is only around when that function is actually running.