Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

printf tip

Status
Not open for further replies.

hbajaj

Programmer
Jan 14, 2001
4
CA
wht will be the output for following line of code

Code:
printf(3+"abcdef");

Output is def

3+ means that leave first 3 char in the quotes and print the rest.
If we use in the string %d or %c (format specifiers ) the it consider it as 2 seprate char(% and d) not 1.
so if code is

printf(3+"%dabcdef");
Then output will be bcdef not cdef..........



 
This is not the behaviour of printf().

It is the pointer arthematic you are doing.

the format string passed is "const char *" type and
when you add 3+"abcdef" like that the pointer is incremented. As it is a char pointer type it will be incremented by 3 chars. Hence effectively the pointer passed is pointing to the char "d".

this is similar to
char * c = "abcdef"
char *p = 3+c;



P S Manjunath
manjunath.ps@chennaimail.ltitl.com

 
I dont' wanna be mean... but... that was a really funny "tip" hbajaj posted there... Its' a really cute "logically based" misunderstanding of pointer arithmetics and printf behavior. Anyway... one should learn from our/others mistakes.

Good luck in the future!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top