1
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.

1
  • Before you decide on the best solution I recommend you research the terms "POD" and "Aggregate", to decide if you need them for this type. 'Args' is currently is a POD type. Going with the solution suggested by 'wrang-wrang' very likely will result in your type not being a POD or Aggregate. The solution suggested by 'ZZ Coder' requires that the type should be a POD. Commented Sep 17, 2009 at 10:47

5 Answers 5

4

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
};
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2

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

For example,

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

  ...

  if (arg.arg2 == 0) // Not set

1 Comment

Rather, memset(&arg, 0, sizeof(arg))
2

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).

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.