elfutbolmola elfutbolmola - 7 months ago 13
Bash Question

Accessing optional arguments in C, with two arguments in one

I need access to

[pid[value]]
, but I'm not sure what the notation even means.

I know how to use
**args
to get arguments given to my program. If I have
[pid][value]
, I can do
args[1]
for
pid
and
args[2]
for
value
, but if I have
[pid[value]]
, I don't know. How do I access both arguments?

Answer

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.