About Lesson
Variables can be defined inside any block, not just functions.
void main()
{
int x = 10;
if (x > 0) {
int y = 1;
while (y < 10) {
int z = 100;
...
}
}
}
Here, the scope of variable y is the “true” part of if statement and the scope of variable z is the while loop. An automatic variable declared and initialised in a bock is initialised every time the block is entered.
Automatic variables including formal parameters override external variables and functions of the same name. Example:
int x = 10;
float y = 3.4f;
int func(double x)
{
char y = 'c';
printf("x = %lf, y = %c\n", x, y);
}
Here, printf will print the value of the parameter x and character ‘c’ corresponding to y.
In practice, it’s best to avoid having the same external and internal names, to prevent any confusion and error.