tags:

views:

129

answers:

4

$3.6.1/3 states-

"The function main shall not be used (3.2) within a program.".

The sample academically motivated program below uses the name 'main' in a couple of ways which I thought are legitimate. This is based on the assumption that 'usage of a function' is related to calling the function (directly/indirectly).

struct MyClass{ 
private: 
   MyClass(){}  
   friend int main(); 
};   

int main(){  
   MyClass m;  
   int (*p)() = main; // but don't do anything 
}
  1. Fair enough, the code shown compiles with gcc/VS 2010.

  2. I am surprised by Comeau's error.

Comeau online gives error while declaration 'p' (i.e while taking address of 'main') but not while declaraing 'main' as a friend.

Who/What is right with respect to C++03?

+6  A: 

C++03 §3.2/2 says:

An object or non-overloaded function is used if its name appears in a potentially-evaluated expression.

It goes on to list what constitutes use of other various types of entities; this is the important one here.

A friend declaration is not an expression.

When the function main() is converted to a pointer and that pointer is assigned to p, that is an expression and it is potentially evaluated (C++03 §3.2/2):

An expression is potentially evaluated unless it appears where an integral constant expression is required (see 5.19), is the operand of the sizeof operator (5.3.3), or is the operand of the typeid operator and the expression does not designate an lvalue of polymorphic class type (5.2.8).

James McNellis
@James McNellis: awesome!
Chubsdad
A: 
peachykeen
A: 

I think that in the first case, the friend function just refers to "some function called main" while in the second case its rather "oh, you mean THE ONE main? I can't allow that".

Eric
+1  A: 

C++03 Appendix C.1 on C++ and ISO C Compatibility says:

Changes in 3.6

Change: Main cannot be called recursively and cannot have its address taken
Rationale: The main function may require special actions.
Effect on original feature: Deletion of semantically well-defined feature
Difficulty of converting: Trivial: create an intermediary function such as mymain(argc, argv.
How widely used: Seldom

Martin York
@Martin York: Sorry, but is this a reference in C++ standard?
Chubsdad