Search code examples
cconstantsc-preprocessordigits

Using constant defined number of digits


I would like to use a constant defined number of digits

    #define DIGITS 10
    printf(%0DIGITSd \n, myvalue)

Will that work ? If not, how can I do it in a simple way ?


Solution

  • You're missing quotes around the string.

    In C, a string is actually specified by a sequence of string literals. So you can do:

    #define DIGITS "10"
    
    printf( "%0" DIGITS "d\n", myvalue );
    

    The preprocessor can also generate strings from other tokens (such as numbers). Check into the stringize operator (#), but I'd recommend only using it if you really need it.