Reputation: 974
#include<stdio.h>
int main(){
int main =22;
printf("%d\n",main);
return 0;
}
output:22 I am defining main as function and variable both even though compiler is not giving error. It should give error "error: redefinition of ‘main’ " . I am not able to understand why this code is working.
Upvotes: 4
Views: 121
Reputation: 2817
#include <stdio.h>
#include <string.h>
void stuff();
main()
{
int val = 10;
printf("from main: %d\n", val);
stuff();
printf("from main: %d\n", val);
stuff();
}
void stuff()
{
int val = 5;
printf("from stuff: %d\n", val);
}
It doesn't matter defining the int val many times as it matters in which scope it's defined, this will output 10 5 10 5 , no errror no bad behavior
Upvotes: 0
Reputation: 22841
It will not give you an error because main
is not a keyword. but main is define 2 times
- Scoping rules come into play.
Upvotes: 7
Reputation: 206717
The declaration of main
inside the function creates a new identifier in the scope of the function. It does not override the main
function which is defined in global scope.
Upvotes: 3
Reputation: 28850
The main function is in the global scope - while the variable main is defined within the function main scope. They're not at the same level, thus there is no conflict.
The int main=22;
line tells the compiler to use (declare) the local variable main - there is no conflict / ambiguity.
Do
int main(){
return 0;
}
int main =22;
on the other hand and you'll get an error.
Upvotes: 3