redeclaring variables

Posted By: iuselitec

redeclaring variables - 02/13/08 06:51

void test()
{
int i = 10;
int i = 10;
}

if you do that with other compilers they complain about the second declaration of the variable. lite-c does not complain but what will happen? does it simply ignore the second int?

you can even do:

void test()
{
int i = 10;
float i = 10;
}
Posted By: Futurulus

Re: redeclaring variables - 02/14/08 04:24

A little bit of experimentation seems to indicate that it replaces the first declaration with the second. It even allocates a new block of memory for the new declaration and initializes it to zero if you don't assign it a value. Interesting, but it shouldn't cause problems--unless the second declaration is on accident, in which case you might not realize you are setting the variable to zero.
Posted By: iuselitec

Re: redeclaring variables - 02/14/08 07:16

but could it cause a memory leak? does the first one get freed correctly?
Posted By: Futurulus

Re: redeclaring variables - 02/16/08 21:18

Actually, I think it is freed correctly. If I write a function that has a multiply defined variable like that, with a script calling a function in a while loop, the addresses of the "two" variables are different (0x0012FDCC and 0x0012FDD0), but these addresses don't move up from call to call, as they would if memory were being left allocated. So I don't think you need to worry about memory leaks.
Code:
int quit()
{
sys_exit(NULL);
}

int no_leaks()
{
int i = 0;

int *p = &i;

int i = 100;

printf("First:\naddr=%p", p);
printf("Second:\naddr=%p", &i);

return 0;
}

int main()
{
on_esc = quit;
while(1)
{
no_leaks();
wait(-5);
}
}


Posted By: iuselitec

Re: redeclaring variables - 02/18/08 10:50

thanks! we could also try it with bigger structs and see if memory raises in the task manager.
© 2024 lite-C Forums