I've read the first array member of argv
will always be the program name.
Is it ever useful to hang on to this? I'm learning, so forgive me please if it is a dumb question.
Do people ever unshift the first member because it is useless (and reset argv
to be one less?), or is leaving it there best practice because people expect it will always be there (and for it to work out of the box with argc
) ?
I've read the first array member of argv will always be the program name.
It should be. C and C++ both require that if argc
is greater than zero, argv[0]
shall either be the program name or an empty string.
Some systems do not necessarily follow this convention in all circumstances (on Windows, for example, you can use CreateProcess
to create a new process and not pass the program name in the command line arguments that are used to populate argc
and argv
).
Is it ever useful to hang on to this?
Sure. If you want to spawn another instance of yourself, for example, or if you want to print your program name (for example in usage instructions).
Do people ever unshift the first member because it is useless, or is leaving it there best practice?
Don't change the actual arguments; the next person who comes along will probably be expecting them to be in their original form.
To be precise, argv[0]
is whatever is passed to exec(2) which is conventionally the program name but could be anything.
Don't unshift it because too many hidden dependencies count on it.
It is expected that argv[0] will always contain the name of the executable. Because of this you should never remove it.
As for whether it's useful, one use for argv[0] is if you want your application to change behaviour based on how it was called.
Busybox, for example, makes use of this on embedded linux systems. Typically you would have a single copy of the executable and create symbolic links to the executable with different names. eg. cp, rm, ls, etc. Busybox then determines which function to perform based on the contents of argv[0].
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