rogerfederer07's blog

By rogerfederer07, history, 21 month(s) ago, In English
int a[100];
int sum = 0;
for(int i = 0; i < 100; ++i) {
    cin >> a[i];
    sum += a[i];
}

and

int sum = 0;
for(int i = 0; i < 100; ++i) {
    int val;
    cin >> val;
    sum += val;
}

My doubt is whether both the code snippets consume same amount of memory ?

Thanks in advance!

Edit : I don't understand why it's getting downvoted despite being a valid doubt.

 
 
 
 
  • Vote: I like it
  • -3
  • Vote: I do not like it

»
21 month(s) ago, # |
  Vote: I like it 0 Vote: I do not like it

The first one is consuming more memory because of the array.

»
21 month(s) ago, # |
  Vote: I like it 0 Vote: I do not like it

Of course not.

You use an array in the first code so it'll consume more memory than the second one.

»
21 month(s) ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

When the variable val goes out of scope, it is deleted from the stack so it is not that new memory is allocated in every iteration for 100 times, therefore, the 2nd one takes less memory. Also, the array might have overhead.