elfutbolmola elfutbolmola - 9 months ago 29
Bash Question

Accessing optional arguments in C, with two arguments in one

I need access to

, but I'm not sure what the notation even means.

I know how to use
to get arguments given to my program. If I have
, I can do
, but if I have
, I don't know. How do I access both arguments?


Optional arguments only make sense when you have sensible defaults. Assuming you do, decide which one is most often required and make it the first one.

char *pid ;
char *value ;

if (argc < 1) {
    value = VALUE_DEFAULT ;
    pid = PID_DEFAULT ;
else if (argc < 2) {
    value = VALUE_DEFAULT ;
    pid = argv[1] ;
else if (argc < 3) {
    value = argv[1] ;
    pid = argv[2] ;

Having positional optional parameters really only works if you have a very restricted set of parameters (which you do) or you use it so often typing in flags or parameter names is never worth the bother.

It's a good idea to be fluent in command line parsing. It's one thing that's not going to change much in the future.