views:

166

answers:

5
static struct Args {
  char*  arg1;
  unsigned arg2;
  unsigned arg3;
  char*  arg4;
} arg;

My program saves command line args to a structure. Sometime all of the members are set... sometimes only a couple of them.

In the case where only arg1 is set, what would the best practice be to do with the rest of the members?

Thanks.

+4  A: 

I'd use a flagged optional type, e.g. Boost.Optional. While you can use NULL for pointers, you may as well use an optional<char *> as well as an optional<int>.

If you insist on using NULL, you may decide that some int values aren't legal inputs (e.g. (unsigned)-1); you could reject them if the user supplies them, and use them to represent "no option supplied".

The essence of an optional wrapper is: boolean flag for whether option is present, and wrapped data type, e.g.:

template <class T>
struct optional<T> {
 T val;
 bool none;
 bool have() { return !none; }
 optional() : none(true)
 optional(T const& val) : val(val),none(false) {}
 void operator=(T const& t) { none=false; val=t; }
 // etc; make none and val private if you wish
};
wrang-wrang
+2  A: 

If you are working in plain c consider using GNU gengetopt, or emulating the approach used therein (which is to have flag variable that tell if optional arguments have been set). The c standards provide you with no support (soon to be released c++ standard).

dmckee
+2  A: 

I would just memset the whole thing. Any 0 value or null pointer are assumed not set.

For example,

  memset(&arg, sizeof(arg), 0);

  ...

  if (arg.arg2 == 0) // Not set
ZZ Coder
romkyns
+3  A: 

Usually when an argument is omitted, some default value is used by the program instead. If it makes sense, just put such defaults into the structure as if they were supplied as arguments.

Alternatively, it's common to set (char *)s to NULL in cases like this. (Note, it's possible to distinguish an empty string "" from NULL, and this may be useful as well.)

Integers are often set to some "invalid" value like 0 or -1 (this depends on which values are valid). For an unsigned you could use 0xFFFFFFFF.

Artelius
+2  A: 

As Artelius pointed out, you could set them to the default values. It is common to set pointers to NULL in such cases. With integers, you would want them to have a value other which will not confuse the rest of the code, like -1.

Ashwin