4

Say, I have

struct Foo
{
    char a;
    char b;
};

void bar(Foo foo);

What's the most succinct way to initialize a struct and pass it to the function? Ideally I would like to write something like

bar(Foo = {'a','b'});

What if Foo was a union?

UPD: My sincere apologies, the question was supposed to be in relation to C++03 only. Also, in this particular case, going away from POD is to be avoided (the code is for embedded system, ergo shorter bytecode is sought after). vonbrand, thanks for the C++11 answer.

NioBium
  • 583
  • 3
  • 10

2 Answers2

5

In C++ 11 you can write:

bar({'a', 'b'});

or:

bar(Foo{'a', 'b'});

(see Stroustup's C++11 FAQ).

g++-4.8.2 accepts this without complaints only if you give it -std=c++11, clang++-3.3 gives an error unless -std=c++11

vonbrand
  • 11,412
  • 8
  • 32
  • 52
1

You could add a constructor to your struct. e.g.

struct Foo
{
    Foo(char a, char b) : a(a), b(b) {}
    char a;
    char b;
};

Then you could call your function

bar(Foo('a', 'b'));

If it was a union, you could have different constructors for the different types of the union.

The Dark
  • 8,453
  • 1
  • 16
  • 19
  • 1
    This is true but now your struct is no longer POD so it has huge ramifications. The C++11 way allows it to remain POD. – StilesCrisis Mar 08 '14 at 01:54