Open In App

Difference between %d and %i format specifier in C language

A format specifier is a special character or sequence of characters used to define the type of data to be printed on the screen or the type of data to be scanned from standard input. A format specifier begins with a ‘%’ character followed by the sequence of characters for different types of data.

In short, it tells us which type of data to store and which to print. Format specifiers are primarily used with scanf() and printf() functions.



For example, If we want to read and print an integer using scanf() and printf() functions, either %i or %d is used but there is a subtle difference in both %i and %d format specifier.

%d specifies signed decimal integer while %i specifies integer of various bases.



‘%d’ and ‘%i’ behave similarly with printf()

There is no difference between the %i and %d format specifiers when used with printf.

Consider the following example.




// C program to demonstrate
// the behavior of %i and %d
// with printf statement
#include <stdio.h>
 
int main()
{
    int num = 9;
 
    // print value using %d
    printf("Value of num using %%d is = %d\n", num);
 
    // print value using %i
    printf("Value of num using %%i is = %i\n", num);
 
    return 0;
}

Output
Value of num using %d is = 9
Value of num using %i is = 9

%d and %i behavior is different with scanf()

%d assume base 10 while %i auto detects the base.

Therefore, both specifiers behave differently when they are used with an input function. So, the value of 012 would be 10 with %i but 12 with %d.

Consider the following example.




// C program to demonstrate the difference
// between %i and %d specifier
#include <stdio.h>
 
int main()
{
    int a, b, c;
 
    printf("Enter value of a in decimal format:");
    scanf("%d", &a);
 
    printf("Enter value of b in octal format: ");
    scanf("%i", &b);
 
    printf("Enter value of c in hexadecimal format: ");
    scanf("%i", &c);
 
    printf("a = %i, b = %i, c = %i", a, b, c);
 
    return 0;
}

Output

Enter value of a in decimal format: 12
Enter value of b in octal format: 012
Enter value of c in hexadecimal format: 0x12
a = 12, b = 10, c = 18

Explanation


Article Tags :