2

I can write

#include <stdio.h>

int main(const int argc, const char * const * const argv) {
    argv = NULL;
    printf("Hello, world\n");
    return 0;
}

And this doesn’t compile because argv is const (which is good).

However a document I read suggested char * argv[argc + 1] as a better way to declare argv. But how can I make it so this declaration style makes argv itself const?

#include <stdio.h>

int main(const int argc, const char * const const argv[argc + 1]) {
    argv = NULL;
    printf("Hello, world\n");
    return 0;
}

This compiles but I’d really like it not to.

17
  • 1
    how can I make it so this declaration style makes argv itself const? You shouldn't do that. argv is not const. Commented Mar 27, 2016 at 17:19
  • 1
    @Matt argv is a pointer argument to main. There's no reason why it can't be declared const, as long as main doesn't change it. That's the whole point of OP's question. Commented Mar 27, 2016 at 17:23
  • argv as a pointer need not be const and the array is defined by the standard to not be const qualified either. See 5.1.2.2.1p2 Commented Mar 27, 2016 at 17:24
  • 1
    @Olaf main is a function. If it wants to restrict one of its arguments to be const, why shouldn't it be able to? I know it doesn't have to declare it const, but it should be possible. It actually exposes a flaw in array parameter notation in C, since the desired effect can be achieved using pointer notation, at the expense of ditching the array size info. Commented Mar 27, 2016 at 17:27
  • 3
    There is no difference between char * argv[argc + 1] and char * argv[] and char ** argv. So why not stick to the last? Commented Mar 27, 2016 at 17:32

1 Answer 1

3

See the C standard, 6.7.3p9:

If the specification of an array type includes any type qualifiers, the element type is so- qualified, not the array type. ...

So, the const cannot be applied to the array name. Either you use the pointer syntax or live with the non-const pointer. Note that this has no impact for correct code on most architectures.

As argv is a pointer to the first element in both versions, see 6.7.6.3p7, there is in fact no difference between char **argv and char *argv[] arguments. You cannot pass an array (as an array) to a function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.