I have a buffer that is declared in a loop. It is initialized on the first iteration. I recently ran the code in Visual Studio 2010 debug and it breaks on a runtime error:
Run-Time Check Failure #3 - The variable 'buffer' is being used without being initialized.
Here is some sample code. It's also available on ideone where it runs successfully.
using namespace std;
int main( int argc, char *argv[] )
{
for( int i = 0; i < 5; ++i )
{
char buffer[5];
if(i == 0)
{
buffer[0] = 'y';
buffer[1] = '\0';
}
cout << buffer[0] << endl;
}
return 0;
}
I thought that the buffer wasn't recreated on every iteration. I know that if I had a vector or something the constructor would be called on every iteration but I thought C types or POD types (if that's the right phrase) were different.
Is Visual Studio correct or is it wrong, I have a bunch of places where there are buffers that are changed on iteration n of a loop and I expected that buffer to be the same on iterations after that until changed again. And they are in gcc but with this recent debug session I'm guessing that's just luck!
Thanks
edit: Found an interesting thread on codeguru where people seem to be split about it:
Variable declaration inside a loop
void f(int b) { int a = b; }, then there is an object created for the variableaevery time you call the function. There's nothing special going on. Objects are dynamic concepts; variables are static concepts. Variables are in the source code, objects are in the running program. It's not a contradiction that a single variable declaration causes the life of many objects.