Search code examples
c++structinitializationanonymous

Anonymous (?) initialization of a struct passed as an argument in C++03


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.


Solution

  • 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