+ 1

Does C get initialised and destroyed everytime the look iterates void display(int* a){for( int I =0;I<5;I++){ int C = a[I];}}

Destruction of data at block scope

27th Jul 2019, 6:01 PM
Mandla Thabethe
Mandla Thabethe - avatar
7 ответов
+ 4
Yes, as per the code fragment, C will be initialized and destroyed 5 times (default behaviour, but compilers are free to use the same address for reinitializing the variable, prevent reallocation or even remove the statement if it serves no purpose, depending on the level of optimization), as its scope terminates after every iteration of the loop. It won't affect execution much in this case, but might have an effect if you were initializing a string or an object of a class with overloaded constructors and destructors that perform various tasks.
27th Jul 2019, 6:19 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
Mandla Thabethe Declaring a variable at the place you use it will help you prevent errors regarding out of scope access, as the variable will not be avaialble outside the scope you defined it in, unless the variable is allocated on the heap or has non-automatic storage duration (like static variables). But if you have an object of a class for which copy construction or assignment is expensive (like a non-optimized, user-defined version of the string class), or if you initialize the variable with a constant value or the return value of a function which returns the same result everytime, it is better to declare the variable in an upper scope.
28th Jul 2019, 3:59 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
0
So will it be better to initialise C outside the loop?
27th Jul 2019, 6:27 PM
Mandla Thabethe
Mandla Thabethe - avatar
0
What if we had a declaration class of some sort would it not make code better organised and efficient?by some degree reasonable to implement which will be inherent to the object itself?
27th Jul 2019, 6:34 PM
Mandla Thabethe
Mandla Thabethe - avatar
0
Lol, it took a while to understand what you mean't, because you used C as the variable. "How does it destroy and initialize C programming language?"
28th Jul 2019, 9:44 AM
Seb TheS
Seb TheS - avatar
0
Lol apologies for the disambigiuty
28th Jul 2019, 10:07 AM
Mandla Thabethe
Mandla Thabethe - avatar