HOWTO: Use #define Constants in printf() Format Strings

Article ID: Q117429

The information in this article applies to:
  • The C Run-time (CRT) included with: - Microsoft C/C++ for MS-DOS, version 7.0 - Microsoft Visual C++ for Windows, versions 1.0, 1.5 - Microsoft Visual C++ 32-bit Edition, versions 1.0, 2.0, 2.1, 4.0, 5.0

SUMMARY

Using #define constants to specify precision or width directly within the printf() format string does not work as expected. The constant identifier is printed literally.

For example, at times, it is convenient to define a maximum output precision or width for printing or scanning values within a given program. The following printf() statement truncates the output string at 20 characters:

   printf( "This is the string: %.20s\n",szBuf );

However, the following statement:

   #define MAXSIZE 20
   printf( "This is the string: %.MAXSIZEs\n",szBuf );

prints the message "This is the string: MAXSIZEs".

MORE INFORMATION

A couple of steps are needed to get the behavior you want:

   #define MAXSIZE 20
   #define STRX(y) #y            // "Stringizes" parameter y.
   #define STR(x) STRX(x)        //  Evaluates x

   printf( "This is the string: %."STR(MAXSIZE)"s\n", szBuf );

First, the constant is evaluated so that it does not come through as the literal constant identifier name ("MAXSIZE"). Then, the STR macro causes MAXSIZE to be evaluated. Finally, the STRX macro uses the # operator to cause the value to be placed in double quotes and concatenated to the format string.

MORE INFORMATION

Below is a simple program that includes the code described above.

Sample Code

   /* Compile option needed: none
    */ 

   #include <stdio.h>

   #define MAXSIZE 20
   #define STRX(y) #y            // "Stringizes" parameter y.
   #define STR(x) STRX(x)        //  Evaluates x

   void main( void )
   {
      char szBuf[17] = { "Howdy, stranger!" };

      printf( "This is the string: %.20s\n",szBuf );

      printf( "This is the string: %.MAXSIZEs\n",szBuf );
      printf( "This is the string: %."STR(MAXSIZE)"s\n", szBuf );
   }
Keywords          : kbCRT kbVC 
Version           : MS-DOS:7.0;WIN3X:1.0,1.5;WINNT:1.0,2.0,2.1,4.0,5.0;
Platform          : MS-DOS NT WINDOWS
Issue type        : kbhowto


Last Reviewed: October 5, 1997
© 1999 Microsoft Corporation. All rights reserved. Terms of Use.