6
#include <iostream>

int main(){
    std::cout << main << std::endl;
    return 0;
}

Why it prints 1 in command line ?

David Mnatsakanyan
  • 455
  • 1
  • 4
  • 15
  • 2
    Out of curiosity, what are you *expecting* this code to print? main in this case is a function pointer. – Jonathon Reinhart Feb 22 '15 at 16:42
  • @JonathonReinhart: Is it? Remember `main` is special... – Deduplicator Feb 22 '15 at 16:45
  • 1
    It is probably undefined behaviour. Thou shalt not name main. See http://stackoverflow.com/questions/2128321/can-main-function-call-itself-in-c/2128727#2128727. – juanchopanza Feb 22 '15 at 16:46
  • 5
    You are not allowed to use `main` in your program. [Most sane compilers will warn you.](http://coliru.stacked-crooked.com/a/f5512d094bedd615) It will still print `1` for the name of a normal function, because the function pointer gets implicitly converted to `bool`. – T.C. Feb 22 '15 at 16:46
  • `main` shall not be _used_ within a program. _used_ i.e. _"the name appears in a potentially-evaluated expression."_ – P0W Feb 22 '15 at 16:50
  • @T.C.: You mean, "The function main shall not be used within a program." which makes it ill-formed. Still, after issuing a diagnostic the compiler is free to accept it with whatever semantics it wants anyway. – Deduplicator Feb 22 '15 at 16:52
  • 1
    related: function pointers will be cast into bool http://stackoverflow.com/questions/25540033/is-visual-studio-buggy-in-printing-the-function-address – phuclv Feb 22 '15 at 17:27

1 Answers1

6

Your program is ill-formed. N4140:

§3.6.1/3 The function main shall not be used within a program. [...]

If we pretend that the program wasn't ill-formed, the most likely explanation is the standard conversions:

§4.3/1 An lvalue of function type T can be converted to a prvalue of type "pointer to T." The result is a pointer to the function.

§4.12/1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

If you insist on doing this, try:

std::cout << (void*)main << std::endl;
  • Don't forget the part where `std::ostream` does not have a `<<` operator that accepts a function pointer with signature `int (*)(void)`, which is why the pointer is being converted to another type at all. – Remy Lebeau Feb 22 '15 at 17:14
  • in [this quuestion](http://stackoverflow.com/a/2741896/995714) I saw `main` was used many times – phuclv Feb 22 '15 at 17:37
  • @LưuVĩnhPhúc That's C. I haven't seen any standard quotations so far that say it's ill-formed in C. –  Feb 22 '15 at 17:39