4
#include <stdio.h> int main() { printf(5 + "abhishekdas\n") ; return 0 ; } 

The output of the program is hekdas . How is it working? Shouldn't it show error? How is it possible to write something like 5 + "abhishekdas" inside printf function ?

3
  • 1
    What kind of error did you expect? Commented Sep 28, 2013 at 11:32
  • @effeffe i thought that how can one add an int to a string . Commented Sep 28, 2013 at 11:48
  • "How is it possible to write something like 5 + "abhishekdas" inside printf function ?" - you take a text editor and type printf(5 + "abhishekdas"). Simple as that. As to why it works: addition is commutative, so 5 + "string" is the same as "string" + 5, which is simple pointer arithmetic. Also, 5["foobarbaz"] works as well, for the same reason. Duplicate hundreds of times. Commented Jan 10, 2015 at 13:34

2 Answers 2

8
5+"abhishekdas\n" ==> "abhishekdas\n"+5 ==> &"abhishekdas\n"[5] ==> "hekdas\n" 
Sign up to request clarification or add additional context in comments.

Comments

4

5+"abhishekdas"

is equivalent to &"abhishekdas"[5], which is the adress of the sixth element of the array.

"abhishekdas" is a string literal: its type is an array type. As every array object, when evaluated in an expression it is converted to a pointer type. So 5+"abhishekdas" is simple pointer arithmetic.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.