Compound Literal

9 03 2012

Today I’ve learned new stuff in C!

Actually, almost every week I learn something new about C or C++ (specially C++ because I’ve been working with that in the lasts months).

Have you heard about Compound Literal (Composto Literal portuguese)??

It’s a nice thing, it’s forbidden at C90 but allowed at C99 and beyond.

Let’s suppose that you have a code like that:

struct cl_demo
{
int pos_a, pos_b;
};

void print_positions(struct cl_demo demo)
{
printf("Pos a %d | Pos b %d\n", demo.pos_a, demo.pos_b);
}

What usually programmer does? Create a struct typed “struct cl_demo” and pass throught parameter to print_positions, right?

But using compound literal, you don’t need do it any more.
You can call the function without creating a new structure just to do that.
Take a look:


int main(void)
{
print_positions((struct cl_demo) {200, 300});
return 1;
}

 

You can still reading more about this at http://drdobbs.com/184401404