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[]);
The main function can be defined with no parameters or with two parameters (for passing command-line arguments to a program when it begins executing). The two parameters are referred to here as argc and argv, though any names can be used because they are local to the function in which they are declared.
A function attribute is specified with the keyword __attribute__ followed by the attribute name and any additional arguments the attribute name requires. A function __attribute__ specification is included in the declaration or definition of a function.
The main function must be declared as a non-member function in the global namespace. This means that it cannot be a static or non-static member function of a class, nor can it be placed in a namespace (even the unnamed namespace). The name main is not reserved in C++ except as a function in the global namespace.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With