Forum guidelines
Ken H
Some confusion of the character constant
Posted By Ken H on 12 Mar 2012
hi all,
   Consider the following problem:

void main()
 char ch='\48';
//Why the above code output is 8?


void main()
 char *s="\ta\018bc";
 for(;*s!='\0';s++) printf("*");
//Why the above code output is 6 *?

thank very much.

Re: Some confusion of the character constant
Posted By Vulpes on 12 Mar 2012  
Multi-character constants are implementation defined in C++ though (FWIW) the documentation for Visual C++ is here:

With the first expression '\48', what seems to happen is that \4 is read as the octal literal 4 but 8 is read literally as it's not an octal digit. However, \4 is then ignored (frankly I've no idea why) and only 8 is printed.

With the second expression "\ta\018bc" we now have a string constant rather than a character constant. Ignoring the terminating \0, this expression has 6 characters namely \t, a, \01 (an octal constant), 8, b and c. Consequently, 6 asterisks get printed as you iterate through them.

Join a Chapter


Custom Software Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.