The printf function is used to print values of basic data types to standard output. The function has a variable number of parameters, but the first parameter is always a constant string that provides the format of the output.

The format string has either literal characters (characters that will be printed on the output) or argument specifiers, which start with the character %. There are argument specifiers to all basic data types in the C language. A quick list is the following:

For example, the following code will print a format string that contains an integer, a float, and a string variable.

int number = 1;
float price = 10.0;
char *message = "hello";
printf("The values are: %d, %f, and %s\n", number, price, message);

Note: printf is not a type safe function, in the sense that it doesn't check the exact type of the argument that is passed corresponds to the type specified in the first parameter. For example, it is legal to write

int x;
printf("value: %s", &x);

and most compilers will compile this code (although some smart corpilers will at least give a warning). However, the function is treating a pointer to an integer as a pointer to a null terminated sequence of characters, which can have disastrous consequences to the program.

To avoid this kind of problems, if you are using C++ always use the iostream classes instead of printf and their friends. If you must use C, be extra careful about arguments to printf-like functions. Some tools, such as the "lint" program, are able to detect some cases of misuse of the printf function.

Article created on 2008-08-19 22:04:14

Post a comment