Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Difference between %d and %i format specifier in C
In C programming, both %d and %i are format specifiers used for integer values, but they behave differently when used with scanf() for input operations. For printf(), they work identically.
Syntax
printf("%d", integer_variable); // Decimal output
printf("%i", integer_variable); // Integer output (same as %d for printf)
scanf("%d", &integer_variable); // Reads decimal integers only
scanf("%i", &integer_variable); // Reads decimal, octal, and hexadecimal
Format Specifier %d
The %d format specifier handles signed decimal integers. For printf(), it displays integers in decimal form. For scanf(), it only accepts decimal input −
Example
#include <stdio.h>
int main() {
int v1 = 7456;
int v2 = -17346;
printf("The value in decimal form: %d<br>", v1);
printf("The value in negative: %d<br>", v2);
return 0;
}
The value in decimal form: 7456 The value in negative: -17346
Format Specifier %i
The %i format specifier works identically to %d for printf(), but for scanf(), it can read decimal, octal (prefixed with 0), and hexadecimal (prefixed with 0x) values −
Example
#include <stdio.h>
int main() {
int decimal = 1327;
int hex = 0x1A3; // Hexadecimal 0x1A3 = 419 decimal
int octal = 0755; // Octal 0755 = 493 decimal
printf("Decimal value: %i<br>", decimal);
printf("Hex value 0x1A3 as decimal: %i<br>", hex);
printf("Octal value 0755 as decimal: %i<br>", octal);
return 0;
}
Decimal value: 1327 Hex value 0x1A3 as decimal: 419 Octal value 0755 as decimal: 493
Key Differences
| Aspect | %d | %i |
|---|---|---|
| printf() behavior | Decimal output | Decimal output (identical to %d) |
| scanf() input | Decimal only | Decimal, octal (0prefix), hex (0x prefix) |
| Usage | Strictly decimal operations | Mixed number base input |
Conclusion
While %d and %i are identical for printf(), they differ significantly for scanf(). Use %d when you need decimal-only input, and %i when accepting multiple number formats.
Advertisements
