Reputation: 31
It is known that a function and a variable can't share the same name.
like this :
#include<stdio.h>
int main;
int main()
{
return 0;
}
This casued by ‘main’ redeclared as different kind of symbol.
But following two files can be compiled successfuly and make me confused.
main.c:
void print_main(void);
int main() {
print_main();
return 0;
}
print_main.c
#include <stdio.h>
char main;
void print_main() {
printf("Output: 0x%x\n", main); //Output: ffffffe9
}
Confusion
What I've tryed
main.c
void print_main(void);
int main() {
printf("%p\n", &main); // 003D12BC
print_main();
return 0;
}
print_main.c
#include <stdio.h>
char main;
void print_main() {
printf("Output: %x\n", main); //ffffffe9
printf("%p\n", &main); //003D12BC
}
Upvotes: 1
Views: 494
Reputation: 180181
It seems like I answered substantially the same question a few days ago. Oh wait, I did. I would close the present question as a dupe if the other's OP had accepted an answer.
Summary:
A conforming compiler must diagnose incompatible declarations of the same identifier in one translation unit, but it is not required to diagnose that issue for declarations in different translation units.
A conforming compiler is not required to reject the program in either case, whether it emits a diagnostic or not, but if it accepts it then the program has undefined behavior.
- I wonder why compiler didn't remind me ‘main’ redeclared as different kind of symbol?
It is not obligated to do so (see above), and separate compilation makes it challenging to do so. Ultimately, this is a quality of implementation issue.
- why I get a strange number "ffffffe9" and what is it ?
Two words: undefined behavior.
- why the strange number changed when I run these files on another IDE?
Again: undefined behavior.
It is not much useful to try to dig into the various ways the program's undefined behavior manifests in different C implementations. Instead, write programs whose behavior is well defined. Especially do not write programs whose behavior you know to be undefined.
Upvotes: 6