Difference between printf() and sprintf() in C

1. Introduction

In C programming, printf() and sprintf() are both functions used for formatted output, but they serve different purposes. printf() is used for printing data to the standard output (console), while sprintf() is used to store formatted data in a string without displaying it.

2. Key Points

1. printf() sends formatted output to the standard output, typically the screen.

2. sprintf() sends formatted output to a buffer or string variable.

3. printf() is commonly used for displaying output to the user.

4. sprintf() is used when you need to format data but not display it immediately.

3. Differences

printf() sprintf()
Displays formatted data on the console. Stores formatted data in a string buffer.
Does not store the output. Does not display the output, but stores it in a variable.

4. Example

#include <stdio.h>

int main() {
    // Example using printf()
    int num = 50;
    printf("Number with printf: %d\n", num);

    // Example using sprintf()
    char str[50];
    sprintf(str, "Number with sprintf: %d", num);
    printf("%s\n", str);

    return 0;
}

Output:

Number with printf: 50
Number with sprintf: 50

Explanation:

1. printf() directly prints "Number with printf: 50" to the console.

2. sprintf() formats the string "Number with sprintf: 50" and stores it in the str buffer, which is then printed to the console using printf().

5. When to use?

- Use printf() when you need to display formatted output directly to the console.

- Use sprintf() when you need to format a string and store it in a buffer for later use, such as constructing a message or a complex string.

Difference between malloc() and calloc()?

Difference between Local Variable and Global Variable in C

Difference between Global and Static Variables in C

Difference Between Call by Value and Call by Reference in C

Difference Between getch() and getche() in C

Difference between printf() and sprintf() in C

Difference between Arrays and Pointers in C

Difference between Structure and Union in C

Difference Between Stack and Heap Memory Allocation in C

Difference Between Macro and Function in C

Difference between = and == in C

Difference Between for loop and while loop in C

Difference Between Linked List and Array in C

Difference between fgets() and gets() in C

Difference between ++i and i++ in C

Difference between struct and typedef struct in C

Difference between int main() and void main() in C

Difference between Character Array and String in C

Difference between break and continue in C

Difference between exit() and return in C

Comments