Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does %d stand for Integer?

I know this doesn't sound productive, but I'm looking for a way to remember all of the formatting codes for printf calls. %s, %p, %f are all obvious, but I can't understand where %d comes from. Is %i already taken by something else?

like image 317
grasingerm Avatar asked Nov 16 '12 01:11

grasingerm


People also ask

Why is %d an integer?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.

Is %d used for integer?

%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.

What does %D stand for in c?

%d is a format specifier, used in C Language. Now a format specifier is indicated by a % (percentage symbol) before the letter describing it. In simple words, a format specifier tells us the type of data to store and print. Now, %d represents the signed decimal integer.


2 Answers

It stands for "decimal" (base 10), not "integer." You can use %x to print in hexadecimal (base 16), and %o to print in octal (base 8). An integer could be in any of these bases.

In printf(), you can use %i as a synonym for %d, if you prefer to indicate "integer" instead of "decimal," but %d is generally preferred as it's more specific.

On input, using scanf(), you can use use both %i and %d as well. %i means parse it as an integer in any base (octal, hexadecimal, or decimal, as indicated by a 0 or 0x prefix), while %d means parse it as a decimal integer.

Here's an example of all of them in action:

#include <stdio.h>  int main() {   int out = 10;   int in[4];    printf("%d %i %x %o\n", out, out, out, out);   sscanf("010 010 010 010", "%d %i %x %o", &in[0], &in[1], &in[2], &in[3]);   printf("%d %d %d %d\n", in[0], in[1], in[2], in[3]);   sscanf("0x10 10 010", "%i %i %i", &in[0], &in[1], &in[2]);   printf("%d %d %d\n", in[0], in[1], in[2]);    return 0; } 

So, you should only use %i if you want the input base to depend on the prefix; if the input base should be fixed, you should use %d, %x, or %o. In particular, the fact that a leading 0 puts you in octal mode can catch you up.

like image 198
Brian Campbell Avatar answered Oct 13 '22 06:10

Brian Campbell


http://en.wikipedia.org/wiki/Printf_format_string seems to say that it's for decimal as I had guessed

d,i

int as a signed decimal number. '%d' and '%i' are synonymous for output, but are different when used with scanf() for input (using %i will interpret a number as hexadecimal if it's preceded by 0x, and octal if it's preceded by 0.)

like image 34
Juan Mendes Avatar answered Oct 13 '22 05:10

Juan Mendes