Table of contents
1.
Introduction
2.
Syntax of printf
3.
Parameters
4.
Return Value
5.
Formatting in C printf
6.
Syntax of Format Specifier
7.
Examples of printf() in C
8.
Frequently Asked Questions
8.1.
What happens if the number of arguments doesn't match the number of format specifiers?
8.2.
Can you use printf to print to a file instead of the console?
8.3.
Is printf part of the C standard library?
9.
Conclusion
Last Updated: Dec 6, 2024
Easy

printf() Function in C

Author Ravi Khorwal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The printf function is an important part of the C language. It allows you to print text, numbers and other types of data to the console. printf is used to display output and format it in different ways. This tool helps you spot errors or just understand better how your program works. 

printf() Function in C

In this article, we'll discuss what the printf function is, how to use it with different data types, its syntax and parameters, formatting options, and different examples. 

Syntax of printf

The syntax of the printf function in C is:

int printf(const char *format, ...);


It takes a string as the first argument, known as the format string. This contains the text to be printed, along with optional format specifiers that define how to format the additional arguments.


The ... in the syntax represents additional arguments that can be passed to printf and formatted according to the format specifiers in the format string. These arguments are variable in number and type.


Let's understand this in detail:

  • The format string is a char pointer (const char *) 
     
  • It is usually a string literal enclosed in double quotes
     
  • It can contain plain text, escape sequences (like \n for new line) & format specifiers
     
  • Format specifiers start with a % symbol & define how the corresponding argument should be formatted
     
  • Any additional arguments after the format string must match the type & quantity of the format specifiers


Some examples of format strings:
 

"Hello World\n"  // plain text with a new line
 

"The result is: %d\n"  // formatting an integer
 

"Name: %s, Age: %d\n"  // formatting a string & integer

Parameters

The printf function can take a variable number of parameters, but at minimum it requires the format string parameter. Lets look at the details on its parameters:


1. format (required) - This is a string that contains the text to be printed to the console. It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments.


2. additional arguments (optional) - Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string. There should be the same number of these arguments as the number of format specifiers.


The additional arguments must match the type specified by their corresponding format specifier. For example, if the format specifier is %d, the corresponding argument should be an int. If the specifier is %f, the argument should be a double.

Some examples with parameters:

printf("Hello");  // just the required format string
 

printf("Number: %d", 42);  // a format string & an int argument
 

printf("String: %s, Number: %d", "Hello", 42);  // 2 arguments of different types


In summary, printf requires a format string and a variable number of arguments that match the format specifiers embedded in that string.

Return Value

The printf function returns an integer value which represents the number of characters printed to the console (excluding the null terminating character). 

If an error occurs, printf will return a negative value. Some possible errors which might shown are:

  • Invalid format specifier
     
  • Mismatch between format specifier & argument type
     
  • Insufficient arguments for format specifiers


Let’s look at a few examples:

int char_count = printf("Hello");  
// char_count will be 5

char_count = printf("Number: %d", 42);
// char_count will be 10

char_count = printf("Float: %f", 3.14);
// char_count will be 11


If the format string or arguments contain errors, printf will return a negative value instead. It's important to check the return value, especially if you are printing user-generated content, as invalid format strings can cause undefined behavior.

Note: In most simple programs, the return value is not captured or used. But it can be helpful for debugging or in more complex formatting situations where you need to keep track of the number of characters printed.

Formatting in C printf

The printf function allows you to format the output in various ways using format specifiers. Format specifiers start with a % symbol and are followed by a character that represents the data type of the corresponding argument.

Some common format specifiers are:

%d or %i - integer

%f - floating-point number

%c - character

%s - string

%p - pointer address

%x or %X - hexadecimal integer


In addition to the data type, you can also specify the width, precision, and length of the output. These are optional and are added between the % and the type specifier.

For example:

%5d - integer with a width of 5 characters

%.2f - floating-point number with 2 decimal places

%10s - string with a width of 10 characters


These are some examples of using format specifiers:

#include <stdio.h>
int main() {
    printf("%d\n", 42);
    printf("%f\n", 3.14159);
    printf("%c\n", 'A');
    printf("%s\n", "Hello");

    int someVariable = 10;
    printf("%p\n", &someVariable);

    printf("%x\n", 255);

    return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

42
3.141590
A
Hello
 0x7ffeebb88c10
ff


By default, printf right-aligns the output. You can left-align by adding a - before the width. For example, %-10s will left-align a string within a width of 10 characters.

Note: Format specifiers give you a lot of control over the appearance of your output, which allows you to line things up, control decimal places, and ensure consistent formatting.

Syntax of Format Specifier

The syntax of a format specifier in printf is:

%[flags][width][.precision][length]specifier


1. % - The format specifier always starts with a percent sign.
 

2. flags (optional) - Flags are used to control the alignment of output and the printing of signs, spaces, and other prefixes. Some common flags are:

- (minus) - left-align the output

+ (plus) - always print a sign (+ or -) for numeric types

0 (zero) - pad with zeros instead of spaces

  (space) - print a space before a positive number
 

3. width (optional) - A number that specifies the minimum number of characters to be printed. If the output is shorter, it will be padded with spaces. If the output is longer, it will not be truncated.
 

4. .precision (optional) - For floating-point numbers, this specifies the number of digits to be printed after the decimal point. For strings, it specifies the maximum number of characters to be printed.
 

5. length (optional) - This specifies the size of the argument. Some common length modifiers are:

h - for short (integer types)

l - for long (integer types)

L - for long double (floating-point types)
 

6. specifier (required) - This is a character that specifies the type of the argument to be printed (e.g., d for integer, f for floating-point, s for string).
 

Few examples are:

%d - integer
%10d - integer with a width of 10
%.2f - floating-point with 2 decimal places
%+d - integer with a sign always printed
%-10s - string left-aligned with a width of 10

Examples of printf() in C

Now, let’s look at a different type of examples that shows the use of printf in C:


1. Printing a simple string:

printf("Hello, World!");
// Output: Hello, World!


2. Printing an integer:

int age = 25;
printf("Age: %d", age);
// Output: Age: 25


3. Printing a floating-point number:

float pi = 3.14159;
printf("Pi is approximately %.2f", pi);
// Output: Pi is approximately 3.14


4. Printing a character:

char grade = 'A';
printf("Grade: %c", grade);
// Output: Grade: A


5. Printing a string:

char name[] = "Ravi";
printf("Name: %s", name);
// Output: Name: Ravi


6. Printing multiple values:

int x = 10, y = 20;
printf("x = %d, y = %d", x, y);
// Output: x = 10, y = 20


7. Printing with width and precision:

int num = 42;
float amount = 123.456;
printf("Number: %5d", num);
printf("Amount: $%.2f", amount);
// Output: 
// Number:    42
// Amount: $123.46


8. Printing with flags:

int neg = -42;
printf("Negative: %-5d", neg);
printf("Negative: %+d", neg);
// Output:
// Negative: -42  
// Negative: -42

Frequently Asked Questions

What happens if the number of arguments doesn't match the number of format specifiers?

If there are more format specifiers than arguments, you'll get unexpected behavior. If there are more arguments than format specifiers, the extra arguments will be ignored.

Can you use printf to print to a file instead of the console?

No, printf is specifically for printing to the standard output (usually the console). To print to a file, you would use fprintf instead.

Is printf part of the C standard library?

Yes, printf is defined in the stdio.h header and is a core part of the C standard library.

Conclusion

In this article, we learned about the printf function in C, which is used to print formatted output to the console. We covered its syntax, parameters, return value & formatting options. We saw how to use format specifiers to control the appearance of different data types & looked at several examples. printf is a versatile & essential function that every C programmer should be familiar with.

You can also check out our other blogs on Code360.

Live masterclass