Is it right to declare a variable inside the loop?

if the loop runs again and again, what will happen with the declarative statement int a;
will it run everytime?

@sirraghavgupta hey Raghav can you please send some cases that you’re asking about it would be great for me to discuss with you.

Example - evaluating maximum value from an array for a number of test cases.

While(t>0){
int sum=0;
int size;
cin>>size;
// read array
// compute the result
}

my doubt is that here the variables are declared inside the loop. so,

  1. in every iteration, the variable will be declared again every time??
  2. will the statement will be skipped?
  3. does this declaration waste the time of the compiler?

what if i do like ----
int size, sum; // declared outside
While(t>0){
sum=0;
size;
cin>>size;
// read array
// compute the result
}

@sirraghavgupta hey in the first case the variables declare again and again and each time a new memory allocated to the variables. but in the second case, variable declare only one. you can apply a loop and print the size of the variable for better understanding.

u asked me to print size… size or value??

@sirraghavgupta size, because when you print size of variables which is declared inside the loop you will find each time data type allocating memory.

but how can i print the size of variables inside the loop. it will come constant always. i would need to print the size of all the variables separately. how will come to know whether the variable has been allocated memory again or not. please mention properly what u want to say. mention a code or output i required.