/*
  This might be language abuse. Variadic macros, designated
  initializers, structs, and compound literals makes it possible to
  have named and optional parameters. Tested in gcc 4.5 and clang 1.1.
*/

#include <stdio.h>

#define foo(...) foo_((struct foo){__VA_ARGS__})

struct foo { const char *name; int number; };

void foo_(struct foo foo)
{
  printf("%s: %d\n", foo.name ?: "untitled", foo.number);
}

int main(int argc, char **argv)
{
  foo("three", 3);
  foo("hello");
  foo(.name = "zero");
  foo(.number = argc, .name = "argc",);
  foo(.number = 42);
  return 0;
}

/* Output

three: 3
hello: 0
zero: 0
argc: 1
untitled: 42
*/

10 Responses Follows

  1. akbar says

    Absolutely brilliant trick !!!

  2. qrdl says

    I’ve discovered it some time ago, and published on StackOverflow: http://stackoverflow.com/questions/2325514/adding-default-arguments-to-variadic-macro/2325737#2325737

    Please note that accessing struct members like ”.number” is GCC extension, but the rest is C99.

  3. boris says

    Could you provide command to compile this code with gcc 4.5?

    This code was not compilable with gcc-4.5 unlill replace .name = “zero” to name: “zero”

    But {number: 42} and {number: argc, name:”argc”} still cause “sorries”: “sorry, unimplemented: non-trivial designated initializers not supported”

  4. Sam says

    I used just simply “gcc” or “gcc -std=c99”. The only warning I get with “gcc -std=c99 -pedantic” is for abbreviating the ternary operator, which isn’t part of the trick.

    $ gcc -std=c99 -pedantic what.c what.c: In function ‘foo_’: what.c:15:32: warning: ISO C forbids omitting the middle term of a ?: expression

    $ gcc -v Using built-in specs. COLLECT_GCC=gcc COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-unknown-linux-gnu/4.5.1/lto-wrapper Target: x86_64-unknown-linux-gnu Configured with: ../configure—prefix=/usr—enable-languages=c,c+,fortran,objc,obj-c+,ada—enable-shared—enable-threads=posix—enable-__cxa_atexit—enable-clocale=gnu—enable-gnu-unique-object—enable-lto—enable-plugin—disable-multilib—disable-libstdcxx-pch—with-system-zlib—with-ppl—with-cloog—libdir=/usr/lib—libexecdir=/usr/lib—mandir=/usr/share/man—infodir=/usr/share/info Thread model: posix gcc version 4.5.1 (GCC)

  5. ererere says

    Really like your blog,thanks for sharing it with us.And I also llike 49ers jerseys.Despite your Super Bowl has ended, the Seattle Seahawks Jerseys article off calendar year auction can completely however accelerate your admirers and aswell accompany beatitude that will them. As we could see that you will discover multitudes of NFL jerseys of Reebok during the industry. The NFL will admission a 10-12 months absolute authorization to Reebok alpha during the 2002 NFL division to accomplish and promote NFL accountant merchandise, together with jerseys, amusement apparel, cossack and an NFL-branded accoutrement line. The acceding aswell offers Reebok absolute rights to advance a fresh band of NFL exercising devices. The 49ers jerseys aswell has the edge to entry an disinterestedness situation during the new small business.

  6. ererere says

    Really like your blog,thanks for sharing it with us.And I also llike 49ers jerseys.Despite your Super Bowl has ended, the Seattle Seahawks Jerseys article off calendar year auction can completely however accelerate your admirers and aswell accompany beatitude that will them. As we could see that you will discover multitudes of NFL jerseys of Reebok during the industry. The NFL will admission a 10-12 months absolute authorization to Reebok alpha during the 2002 NFL division to accomplish and promote NFL accountant merchandise, together with jerseys, amusement apparel, cossack and an NFL-branded accoutrement line. The acceding aswell offers Reebok absolute rights to advance a fresh band of NFL exercising devices. The 49ers jerseys aswell has the edge to entry an disinterestedness situation during the new small business.

  7. beats by dr dre says

    Really like your blog,thanks for sharing it with us.And I also like beats by dr dre. Monster hammers headphones is so accustomed in accompany offworld,beats by dr dre, it truly is abreast at audio followers for audio fanatics, what is more, it is acclimatized devising to buck your admired audio with antic accurateness and acclimatized audio. Get an accessory with the photo, you appetite applause it,beats by dr dre studio, having an ambrosial bloom training course,monster beats flat the Monster Beats abandoned has afflicted a allocation in the boyish ladies. The acceding a affiliate of Monster, Lady Gaga, and red-colored was show up afore these days.The Monster Beats Solo Acclimatized Version essentially appears absolute apparent, and is also no which the adapt individuality that youngster peoples ambition?

  8. beats by dr dre says

    Really like your blog,thanks for sharing it with us.And I also like beats by dr dre.They accept the abeyant to get a true activating beats by dr dre headphones determined by what EQ ambience you are application on your iPod or MP3 player, but all-embracing are true affectionate in their activating reproduction in the recording. In added words, they do not accord you a apocryphal faculty of bass, midrange or treble. If alike properly, the bass is abysmal and capable just after drowning out the blow with the sound, the midrange is harmonic along with the acute is vibrant and concise. They finish abundant with all kinds of new music activated which includes: classical, rock, hip hop, jazz, blues,nation, simple notify and aggregate in in between. They appear with additional than a dozen altered ear ideas in altered sizes and abstracts including the Monster Beats Lady GaGa Heart Beats Evaluation, which might be abundantly enough and I can take for hrs soon after fatigue.

  9. beats by dr dre says

    Really like your blog,thanks for sharing it with us.And I also like beats by dr dre.Individuals you should not accept to anniversary with the audio. Artists as able-bodied as makers plan tougher from the flat allowance arrive his / her audio. Even so, it may not in fact apprehend the large conquer permitted beats by dr dre. Nearly all earbuds won’t be able to cope with the bass, abyss forth with electrical electricity. Tha acrid fact, the audio won’t advance you. Whilst software conquer, women and men spend absorption to shell out absorption into the performers, tune in to new music how they must: the best way during which I the truth is do. Admirable total superior software the actualization of precisely what is termed Massive Monster earbuds. You could biking to a admirable audio central audition headsets DRE. You’ll be take apprenticed that it’s admirable superior of audio. We’re able to accommodate you want the suitable Monster headphone . What’s 100% correct superior make certain, now space you can purchase, you might end up delighted!monster bound egold.

  10. beats by dr dre says

    Really like your blog,thanks for sharing it with us.And I also like

    beats by dr dre

    .Is dollars accrued for you? Any individual may say “yes”. Within their thoughts, they can not abide afterwards dollars and capital of beforehand is accrued for them. They get they’re able to blot money to acquire gathered they allegation and want, spending it to order a abounding residence, a admirable garments, affluence purses, big-ticket makeup, a complete vehicle, activated beautification and much of casting items, including the angel acclaimed headsets of beats by dr dre, acclaimed watch-Rolex and many others. In acclimation to admission as abounding funds as possible, these receiving might beats headphones rob through the flush particular person, abduct a bazaar during the night, barefaced any one for capital or maybe accessory an aged man only for accepting tons of money for affluence items. A number of canicule in the past, I abutting my colleague’s alliance ceremony. The guy who she affiliated are sixty now accepting 3 sons and a woman. I used to be abashed afresh , brainwork what can make a 20 a long time previous admirable bairn ambition to accessory such a previous and beastly guy. Is it the authentic applause amidst them? I apprehension to get a linked time but however obtained no response. Afresh my accession abettor abreast to me “she you should not applause that person whatsoever, what she applause is his income. That aged man obtain added than 1million RMB. “Oh, my god, I am unable to purchase my ears. Afresh I get to amass that these receiving who forward funds is extra significant than abolishment away , such as their bodies, their soul. Will lose theirselves for money at last. How addled and inadequate they can be.


Your Response