Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of declaring the main function's formal arguments as "int argc, char* argv[argc+1]"?

Tags:

c

semantics

argv

I typically declare the main function's formal arguments as either int argc, char* argv[] or int argc, char** argv to take in the actual arguments from the command line. But I noticed a senior C programmer, who also happened to be a member of the ISO committee and co-author of the C23 revision, uses int argc, char* argv[argc+1], or int argc, char* argv[argc]. What is the point of doing that?

like image 928
Bobby Avatar asked Oct 20 '25 02:10

Bobby


2 Answers

What is the point of doing that?

For people and static code analyzers, the char* argv[argc+1] correctly points out that arg[] may be accessed (e.g. read the pointer) for indexes [0...argc].
Note: argv[argc] is expected to be NULL.

C99, C23 and optionally C11, C17, see the 4 as equivalent.

like image 181
2 revs, 2 users 91%chux Avatar answered Oct 21 '25 16:10

2 revs, 2 users 91%chux


The following parameter declarations are equivalent:

  • int argc, char* argv[argc]
  • int argc, char* argv[argc+1]
  • int argc, char* argv[]
  • int argc, char** argv

This equivalence is spelled out in section 6.7.6.3p7 of the C standard:

A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation. If the keyword static also appears within the [ and ] of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many elements as specified by the size expression

By the above paragraph, the first three cases are adjusted to be equivalent to the fourth. And as there's no static qualifier in any of those cases, it doesn't fall under any exceptions.

The developer likely did this as a form of internal documentation to illustrate the sizes of these arrays.

like image 22
dbush Avatar answered Oct 21 '25 17:10

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!