0

In an Interview, I was asked the output of the following code snippet:

printf("%d", "computer");

I am a c# developer and earlier I had learned C too, but when this question was asked, I had no clue. When I run the same question in windows 10 computer (64-bit), it is giving putput as

3571712

Please give reasons why this is happening.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
vivek
  • 1,595
  • 2
  • 18
  • 35
  • See also: [this question](http://stackoverflow.com/questions/31380628/how-printf-works-in-case-of-type-mismatch-with-type-specifier) and [this question](http://stackoverflow.com/questions/33648596/why-are-arguments-which-do-not-match-the-conversion-specifier-in-printf-undefine). – Paul R Mar 14 '17 at 07:34
  • 3
    Either it was intentionally a tricky question to see if you knew that the code doesn't make sense, or it was unintentionally a complete crap question, in which case you didn't want that job anyway. The correct answer is _not_ "it will print the address of the string literal", because it uses the wrong format specifier for that. – Lundin Mar 14 '17 at 07:49

4 Answers4

4

It doesn't "work", what you observe is an outcome of undefined behavior.

Quoting C11, chapter §7.21.6.1/p9

[...] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

In your case, the conversion specifier is %d which expects an argument of type int but you're supplying a char*, and they are not the compatible type, hence the UB.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
4

well value of "computer" is memory address where that string is stored. It could be value of that address is: 3571712 (But you should not rely on this - see below).

But to print memory address void* you should use %p format specifier. And using incorrect format specifiers is undefined behavior.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
2

In an Interview, I was asked the output of the following code snippet [...]

Your answer could have been:

a. "This is undefined behavior"

b. "A number will most likely be printed, but I cannot tell you which number because I do not know where the string is stored, as the string's address will be attempted to be interpreted as an integer by the printf function".

c. "Which platform? Which compiler?"

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
0

It will not work it's giving the garbage value of these variables. And the main reason is that we use "%d" for the output of int not for string.

Iqbal Butt
  • 196
  • 2
  • 15