Here's an example:
while (i < 10)
{
int j = 1;
string k = "hello.";
}
j is a primitive data type and k is an object. According to Do built-in types have default constructors?,
So non-class types (including fundamental types, array types, reference types, pointer types, and enum types) do not have constructors.
And according to Declaring Variables inside Loops, good practice or bad practice? (2 Parter),
the constructor and destructor must be executed at each iteration in the case of an object (such as std::string).
However, variable declaration within the while loop C/C++ says,
while(i--) { int i=100; // gets created every time the loop is entered i--; printf("%d..",i); } // the i in the loop keeps getting destroyed here
I've learned that when a function is called (such as main()
by the operating system), all local variables are created at the start of the function and destroyed at the end of the function. The above while loop quote is saying that the primitive data type i
is being created when it is declared in the while loop block and destroyed at the end of the while loop block for each iteration.
Is this really true? #1 Are primitive data types declared in the while loop block being allocated for each iteration of the while loop? #2 Am I wrong to assume that these declarations in a while loop should be created at the start of the function the while loop block is contained in?
I'm looking for a detailed explanation, not just yes or no.
i
is declared outside of the while loop but assigned 100 inside it. – squill25int
will be allocated space on the stack, and that space will simply be re-used each time round the loop. The value100
in your example will just be re-copied into it at the start of each loop iteration. Try taking a look at the assembly code generated by your compiler, or step through with the assembly inline in the debugger (if your IDE supports that). You'll see exactly what's going on. – Baldrick