function returning pointer

plz explain the output

1
2
3
4
5
6
7
8
  #include<stdio.h>
char* fun()
{ return("samsung india");
}
int main()
{
printf("%s",printf("electronics")+fun());
}
printf returns the number of characters written. This is added to the pointer to a string returned be fun(). Hence the last part of "samsung india" starting from the length of "electronics" is written after the word electronics itself.

Obfuscated code like this should be avoided in a serious program
That code makes no sense.

Line 3 returns a pointer to the C-string "samsung india". Since that is a const literal string, some compilers "may" choose to place it in a global literal pool. However, I don't believe there is any guarantee that all compilers do that and the string may not remain in existence when fun() has exited.

The inner printf is evaluated first.
 
printf("electronics")+fun()

That will print the string "electronics" to stdout. The return value of the printf is the number of characters printed (11). That will be added to the return value from fun() which may be the pointer to the string "samsung india", resulting in a pointer to "ia". This is then passed to the outer printf, which should then print the "ia". The final output will be "electronicsia" IF the pointer returned by fun() is valid, otherwise it could be garbage.
thnx alot
Topic archived. No new replies allowed.