C/Sir, Please send the reason for the output
Expert: Zlatko - 5/30/2011
QuestionHi Sir,
Please look at the output of the program once.
#include<stdio.h>
#include<conio.h>
void main()
{
int x='\7';
clrscr();
printf("%d",x);
getch();
}
The output for the program is 7.
But
If the value of x='\8' the output is 56.
If the value of x='\18' the output is 14337.
If the value of x='\28' the output is 14338.
If the value of x='\38' the output is 14339.
If the value of x='\48' the output is 14340.
If the value of x='\58' the output is 14341.
I know that a backslash character followed by one to three octal digits (any digit from 0 to 7).
My question is why the compiler is printing such a larger value if the third digit is more than 7 (8 or 9).
Please send me the answer if you know.
Thanks in Advance.
AnswerHello Murali
You are correct that a backslash followed by one to three octal digits will place the value of the octal number into a byte. If the digit is not a valid octal digit, then what happens is up to the compiler. In the Microsoft and the GNU compilers, the ASCII value of the digit is placed into the byte.
When you have x='\58', the first byte of x is 5, and the second byte of x will be the ASCII value of the character '8', which is, decimal 56, or hex 38. It is much easier to understand what is happening if you print out the hex digits instead of the decimal digits because in hex, every two digits is a byte. Use
printf("%x", x)
On my system, I get an output of 538. You can see that the 5 came from the \5, and the 38 came from the hexadecimal ASCII value of the character '8'
On your system, you will probably see a printout of 3805, because your system stores integers in reverse order. That is why you are seeing the decimal printout of 14341. The 3805 in hex is the same as 14341 in decimal.
I hope that helps you to understand what is happening.
Best regards
Zlatko