1

Why does cout<<main; printing 1 on my computer? I thought it would print the address of main. But when I use printf("%x",main); I get different output.

Edit:

I tried std::cout for other functions. I'm getting 1 for every case.

Alex
  • 1,178
  • 3
  • 9
  • 24

2 Answers2

6

It is nothing but undefined behavior. It is an example of a code whose behavior is unpredictable.

Vivek Sadh
  • 4,230
  • 3
  • 32
  • 49
  • 3
    Citation, please. Does the Standard forbid taking the address of `main`? – John Dibling Jul 12 '13 at 17:07
  • 3
    @JohnDibling, The standard forbids using `main`. 3.6.1/3 There was another question on SO about whether taking the address of it was using it, and I believe the consensus was that it was. edit: http://stackoverflow.com/questions/15525613/is-it-illegal-to-take-address-of-main-function – chris Jul 12 '13 at 17:07
  • Great. But in a case like this it's quite easy to explain what implementations do (just take the address of `main`, without acknowledging that `main` is special) and why it gives the output it does, because the implementation's behavior is consistent even though that's not guaranteed by the standard. I'd say adding that explanation is worthwhile (of course, the UB should still be mentioned). –  Jul 12 '13 at 17:10
  • 1
    @chris: Got it, thanks. I knew "using" main was forbidden, but I didn't know what "using" meant in this context. Now I do, so thumbs up. – John Dibling Jul 12 '13 at 17:14
4
void foo(){};
cout << foo << endl; 

A function pointer will be converted to bool, unless use it like this:

cout << reinterpret_cast<void*>(foo) << endl;

EDIT: this is undefined behavior, main can not be used like other function pointers.

C++11(ISO/IEC 14882:2011) §3.6.1: Main function

3 The function main shall not be used within a program. The linkage (3.5) of main is implementation-defined. A program that defines main as deleted or that declares main to be inline, static, or constexpr is ill-formed. The name main is not otherwise reserved. [ Example: member functions, classes, and enumerations can be called main, as can entities in other namespaces. —end example ]

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • As far as I know, the standard doesn't guarantee the cast to `void *` will work (well, of course, seeing as how it's a `reinterpret_cast`, but I'm talking about `void *` and function pointer compatibility in general). It's worth keeping that in mind. – chris Jul 12 '13 at 17:20