What argv = NULL means?

  • A+

I'm trying to make arguments information umodifiable.

#include <stdio.h> #include <stdlib.h>  int main(const int argc, const char* const argv[]) {   //argc = 1;         // error: assignment of read-only parameter 'argc'   //argv[0] = "argv"; // error: assignment of read-only location '*argv'   //argv[0][0] = 'a'; // error: assignment of read-only location '**argv'   return EXIT_SUCCESS; } 

Now when I do this,

argv = NULL; // no compile-time error 

the compiler makes silence.

What does the statement actually do? How can I prohibit my codes from doing that?

Well, first of all, don't do it.

I refer to existing answers for how you would do it, they explain the different levels const can be applied and how to write it in straight pointer syntax as well as in "disguised as an array"-syntax. That's definitely good to know.

But here it comes: main is very special. According to the C standard, it doesn't have a prototype, but the definition should take one of two forms only. Here's the original text, from N1570, the latest draft to C11:


The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;10) or in some other implementation-defined manner.

The footnote 10 even explains what equivalent means here:

Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as char ** argv, and so on.

But as for adding some consts, look for example at § p2:

For two pointer types to be compatible, both shall be identically qualified and both shall be pointers to compatible types.

(emphasis mine). const is a type qualifier. So const char ** is not compatible with char **. You define a main that doesn't conform to the C standard any more. Therefore, just don't do it. Use const correctness inside your program, but don't try changing the interface for program startup.

Side note: exactly the one const you're asking about here might be ok, because it applies to the pointer itself, which is just a local variable to the function (as parameters are always by value in C function calls). So it doesn't change the function's interface. That's why in practice, nobody bothers adding such consts. It's not important for calling code whether a function modifies its locals or not.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: