I have been trying to understand the printf functionality for octal numbers.
If I write the code as:
int main()
{
char *s = "\123";
printf("%s", s);
}
It gives me an output as S which actually is correct since ASCII of S is 123 in octal.
But how does the compiler identify the sequence of numbers to convert from octal? For example:
char *s = "\123456"
would give an output as S456.
Is it that it takes maximum three numbers for octal conversion?
Is there a maximum limit within which the octal should be given (the maximum three-digit octal number would be 777).
Now since there are max 255 ASCII characters (octal 377) then when I try to print 777 it prints a typical � ASCII character, which is presume may be since there is no such ASCII assigned to this number.
Also is this functionality a compiler/OS dependent?
Yes. Three digits are the maximum for an octal character literal. From the spec 6.4.4.4 Character constants:
The maximum octal escape sequence is
\777as you mention. There is no maximum limit for a hexadecimal escape sequence as you can see from the spec quote above.There are only 128 ASCII characters (0-127). That means you can use octal
\000through\177for ASCII. If you use a different character set, you might be able to go to\377in an 8-bit char, and all the way to\777(or higher, using hex escape sequences) for awchar_t. The spec says:On most machines,
unsigned charis an 8-bit type, limiting your octal escape sequence to\377in that context and the hex sequence to\xff. In the case of a 32-bitwchar_tcontext, the hex sequence could be as high as\xffffffff.