C Programming printf() Function
Last modified by Microchip on 2023/11/09 09:06
Syntax
printf("ControlString", arg1, …, argN);
Key Points
- Prints ControlString to Standard Output (the terminal on a PC, typically a Universal Asynchronous Receiver Transmitter (UART) on microcontrollers)
- The MPLAB® X IDE Simulator uses the UART1 Output window to display text written to the UART using printf()
- All comma-separated parameters are optional except for ControlString
- The argument parameters (arg1, …, argN above) can be variables or other data to be embedded within ControlString
- Placeholders are put in ControlString to indicate where the value of an argument parameter should be inserted
- Placeholders indicate the position in string and format to be used in printing data embedded within ControlString
- printf() requires a huge amount of memory. Best used for debugging only unless you need all of its functionality
1 {
2 int a = 5;
3 int b = 10;
4 printf("a = %d\nb = %d\n", a, b);
5 }
2 int a = 5;
3 int b = 10;
4 printf("a = %d\nb = %d\n", a, b);
5 }
The code above would produce the following output:
a = 5
b = 10
_
b = 10
_
Where "_" indicates the position of the cursor at the end of the operation.
- The code in Example 1 defines two variables: a and b
- We want to print their values as part of a string that indicates which value goes with which variable
- The ControlString is "a = %d\nb = %d\n"
- Each %d is a placeholder that indicates where one of the arguments should be inserted and how it should be formatted when printed
- The value of a is inserted at the position of the first %d and the value of b is inserted at the position of the second %d
- The d in the %d is called a format specifier or a conversion character and indicates that the value should be printed as a signed decimal integer
- The \n is an escape sequence indicating that a new line should be inserted, causing the cursor to go down to the next line before continuing to print
Format Specifiers
Format Specifier | Meaning |
---|---|
%c | Single character |
%s | String (all characters until '\0') |
%d | Signed decimal integer |
%o | Unsigned octal integer |
%u | Unsigned decimal integer |
%x | Unsigned hexadecimal integer with lower case digits (e.g. 1a5e) |
%X | Same as %x but with upper case digits (e.g. 1A5E) |
%f | Signed decimal value (floating point) |
%e | Signed decimal value with exponent (e.g. 1.26e-5) |
%E | Same as %e but uses upper case E for exponent (e.g. 1.26E-5) |
%g | Same as %e or %f, depending on size and precision of value |
%G | Same as %g but will use capital E for exponent |