0

When using the printf function, and I want to reference an integer, does it matter if I use %i as opposed to %d?

For example, here are two lines of code that presumably do the same thing.

  1. printf("I have %i pets\n",n);
  2. printf("I have %d pets\n",n);

The walkthrough for Water (in PSet1) shows the use of %i, but I see elsewhere on the web that %d is generally preferred. Another source doesn't even offer %i as a placeholder option.

2

See this question and this question.

Like the questions (and their answers) said, they are the same when you, say, printf one. I used this code:

int number = 10;
printf("My favorite number is %i\n", number);
printf("My favorite number is %d\n", number);

And it outputted the same thing: My favorite number is 10.

I'm not very experienced at using %d (I mainly use %i because that's what CS50 mainly used) but, as far as I can tell, the main difference between them is when using scanf. I made a test program below using scanf.

int number;
printf("This is when we use i as a placeholder!\n");
scanf("%i", &number);
printf("number: %i\n", number);
int number2;
printf("This is when we use d as a placeholder!\n");
scanf("%d", &number2);
printf("number: %d\n", number2);

What does this print when we input 0100? We know 0100 is simply 100, but this is what the program prints:

This is when we use i as a placeholder!
0100
number: 64
This is when we use d as a placeholder!
0100
number: 100

According to https://stackoverflow.com/questions/1893490/difference-between-format-specifiers-i-and-d-in-printf (the first link), this is because:

these are different when used as input specifier e.g. with scanf, where %d scans an integer as a signed decimal number, but %i defaults to decimal but also allows hexadecimal (if preceded by 0x) and octal if preceded by 0.

The links I provided should explain a little bit more about the difference between %d and %i. I hope this helped you!

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .