-2

In a well-known article by Ken Thompson, ( http://users.ece.cmu.edu/~ganger/712.fall02/papers/p761-thompson.pdf )

in figure 1, that formats printf with decimal %d

printf("\t%d, \n", s[i]);

Why would that be done? Shouldn't it have been %c with character format? Why not? Was printf different during that time? Which version of C is the one in figure 1 in the article?

4
  • 1
    char is an integer type, and such printable with format specifiers for integers. Type promotion rules cause it to be converted to int when passed on a variadic argument list, which makes %d a valid format specifier for char. Strictly speaking, %hhd is preferred for char, but this might have not existed back then; this is probably the only part that might be retro-specific. Commented Aug 30, 2021 at 11:39
  • 1
    This sounds like a straight CS question (and rather clear when reading the program at whole (check the data definition) / paper ). Not sure what the retro part here should be.
    – Raffzahn
    Commented Aug 30, 2021 at 12:02
  • @Raffzahn It doesn't say which version of C is used in the article. Usually C89 is the oldest standard I read about. Before that it was "K&R C" Commented Aug 31, 2021 at 15:00
  • @NiklasR. This seems much like a question about a programs intend - in this case printing the decimal value of each byte in an array (so it can be examined). It works with any C version (supporting printf). I can not see any compiler issue and none was brought up. It's a straight CS issue.
    – Raffzahn
    Commented Aug 31, 2021 at 21:00

2 Answers 2

3

%d prints a number, %c prints the character represented by that number. For example, if s[i] evaluates to 65, %d prints 65 but %c (on ASCII-based systems) prints A.

The code listing represents a program that outputs its own code again. But it doesn't output literally the same program in this case. In C, a character constant like '0' gets translated into a number (48, on ASCII systems). So writing 48 here instead of '0' gives the same behavior. Note that the loop only deals with the array of characters (which is not shown completely in the PDF).

0

In the code presented in the linked talk, the %d is used to write the values that populate the char s[] array. The values in the array are integers (8-bit signed to be specific) and for initialization C requires them to be given as strings of numeric characters1. If the values were represented as the actual characters they represent they would need to be single-quoted (e.g. '/', as shown in the figure). Note that the next line (printf("%s", s);) does output the array's values as binary characters (e.g. the decimal number 65 is output as the single character A, not the two characters 652).

1 Yes, this is slightly simplified; e.g. octal notation, etc. can also be used.

2 Assuming the compiler is using the ASCII character set.

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