Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaration inside a loop

Tags:

c++

c++14

In for loop like below

for(int i=0; i<n; i++) {
  vector<int>v(100);
}

In this i have a doubt that

  1. for each loop will the vector will be declare again and again? If yes why it do not causes problem(because if we redeclare same thing it cause problem like two time int x;).

  2. do the size keep on increasing on each loop till the end, in above or for such loop

for(int i=0;i<10000;i++) {
 int k;
}
like image 360
You Know Who Avatar asked Dec 06 '22 08:12

You Know Who


1 Answers

for each loop will the vector will be declare again and again?

No.

There is only declaration but the object is constructed in each iteration of the loop and destructed in each iteration of the loop.

The following is illegal because there are two declaration of the variable.

for(int i=0;i<n;i++)
{
   vector<int> v(100);
   vector<int> v;
}

do the size keep on increasing on each loop till the end, in above or for such loop

It's not clear what you mean by that. Whose size are you talking about?

The size of the code generated by the compiler? That does not change.

The size of memory used by the computer at run time? That does not change either.

Does it take longer to run? Yes.

like image 150
R Sahu Avatar answered Dec 27 '22 19:12

R Sahu