+ 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
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.
+ 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.
0
So will it be better to initialise C outside the loop?
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?
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?"
0
Lol apologies for the disambigiuty