From: david.brown@hesbynett.no   
      
   On 05/02/2026 20:05, Keith Thompson wrote:   
   > David Brown writes:   
   > [...]   
   >> How many people do you know who have actually written and use a   
   >> C11 print system using _Generic and variadic macros? I don't know   
   >> any. (I've written simple examples as proofs of concept, posted   
   >> in this group, but not for real use.) It turns out that people   
   >> /don't/ have to have workarounds. "printf" has its limitations -   
   >> there's no doubt there. But it is good enough for most people   
   >> and most uses.   
   >   
   > I recently played around with an attempted framework using _Generic.   
   > The goal was to be able to write something like   
   >   
   > print(s(x), s(y), s(z));   
   >   
   > where x, y, and z can be of more or less arbitrary types (integer,   
   > floating-point char*). The problem I ran into was that only one of   
   > the generic associations is evaluated (which one is determined at   
   > compile time), but *all* of them have to be valid code. There's a   
   > proposal to change this for C 202y.   
   >   
   > I didn't spend a lot of time on it.   
   >   
      
   My experiments used a variadic macro so that :   
      
    print(x, y, z);   
      
   would be turned into something akin to :   
      
    print_generic(x);   
    print_generic(y);   
    print_generic(z);   
      
   The "print_generic" _Generic macro would then lead you to :   
      
    print_charp(x);   
    print_double(y);   
    print_int(z);   
      
   The difference is then that you get multiple individual print calls,   
   rather than one single one. For some uses, that could be a problem -   
   for other uses, it could be fine. (For my own needs, it's actually   
   quite okay - often what I will do is have a fixed-size local variable   
   buffer, built up a debug string in that, then pass the buffer on to a   
   serial port output routine. The main "print" macro would have this   
   extra code before and after the print_generic macro calls.)   
      
   It would also be possible to do something with _Generic macros to turn   
   the different items into strings. You could allocate the memory for the   
   strings with VLAs (or alloca, if you want to allow that). I haven't   
   tried that, but maybe it's something for a rainy day.   
      
   The most annoying thing about it all, however, is that there is no way   
   to extend a _Generic macro later. You have to put all the types you   
   want in the one place.   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   
|