helloworld
helloworld

Reputation: 12

Attributes for main function parameters

Can I use attributes for main function parameters or is it implementation defined?

Looks like main function has only 2 supported forms without attribute-list while the general function declaration syntax does have it.

Example:

int main([[maybe_unused]] int argc, char* argv[]);

Upvotes: 12

Views: 823

Answers (2)

cigien
cigien

Reputation: 60218

Can I use attributes for main function parameters or is it implementation defined?

From dcl.attr.grammar:

For an attribute-token (including an attribute-scoped-token) not specified in this document, the behavior is implementation-defined.

Since the attribute appertains to the parameter, and that affects the declaration of main, the behavior of such a program is implementation-defined, and is not portable across conforming implementations.

For your example of [[maybe_unused]], this attribute is specified in dcl.attr.unused. There appears to be no wording that this attribute affects the type of a variable declaration, or has any other semantic effect on the behavior of the program, so this program is portable.

Upvotes: 3

Bernd
Bernd

Reputation: 2221

Indeed there is no explicit requirement that attributes must be accepted for main function parameters basic.start.main.

But on the other hand if you read dcl.attr.unused#5 you can't find anything special for main which says that is not allowed there.

This attribute must be known by a compiler to be C++17 conformant, but even unknown attributes should not cause errors. You can find this in the standard:

Any attribute-token that is not recognized by the implementation is ignored. dcl.attr#grammar-6

Unfortunately attributes can cause sometimes errors (even if they shouldn't). See for expamle this issue: GSL_SUPPRESS.

In practice your code is accepted by all major compilers without a warning Godbolt. Therefore I would say it is okay. But because it is allowed to have a main function which takes no arguments I would prefer that.

Upvotes: 7

Related Questions