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

#include<stdio.h>
void main()
{
 char ch='\48';
  printf("%c\n",ch);
}
//Why the above code output is 8?

second:

#include<stdio.h>
void main()
{
 char *s="\ta\018bc";
 for(;*s!='\0';s++) printf("*");
}
//Why the above code output is 6 *?

thank very much.

AuthorReply
Re: Some confusion of the character constant
Posted 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.


SPONSORED BY

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.