A format specifier is a sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the stream and stored into the locations pointed by the additional arguments. In short it tell us which type of data to store and which type of data to print.
For example — If we want to read and print integer using scanf() and printf() function, either %i or %d is used but there is subtle difference in both %i and %d format specifier.
%d specifies signed decimal integer while %i specifies integer.
%d and %i behave similar with printf
There is no difference between the %i and %d format specifiers for printf. Consider a following example.
// C program to demonstrate
// the behavior of %i and %d
// with printf statement
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);
Run on IDE
Output: Value of num using %d is = 9 Value of num using %i is = 9
%d and %i behavior is different in scanf
%d assume base 10 while %i auto detects the base. Therefore, both specifiers behaves differently while they are used with an input specifier. So, 012 would be 10 with %i but 12 with %d.
- %d takes integer value as signed decimal integer i.e. it takes negative values along with positive values but values should be in decimal otherwise it will print garbage value. Consider a following example.
- %i takes integer value as integer value with decimal, hexadecimal or octal type.
To enter a value in hexadecimal format — value should be provided by preceding “0x” and value in octal format — value should be provided by preceding “0”.
Consider a following example.
// C program to demonstrate the difference
// between %i and %d specifier
a, b, c;
printf("Enter value of a in decimal format:");
printf("Enter value of b in octal format: ");
printf("Enter value of c in hexadecimal format: ");
printf("a = %i, b = %i, c = %i", a, b, c);
Run on IDE
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
The decimal value of a as 12 is 12
The decimal value of b as 12(octal) is 10
Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/difference-d-format-specifier-c-language/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at
http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements