Skip to content
Related Articles
Open in App
Not now

Related Articles

Octal numbers in c

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 29 Aug, 2017
Improve Article
Save Article

There are some less known facts in C related to octal numbers. Let us look at the below example code first.

Examples:




// program to show octal number interpretation
#include <stdio.h>
  
int main()
{
    int x = 012;
    printf("%d", x);
    return 0;
}

Output:

10

Surprisingly the output is not 12. This happens because an integer digit preceded by 0 is interpreted as an octal number. An octal number for decimal value 12 is 10. But what if x equals 092 well then the compiler will show an error because 92 is not a valid octal number.

Octal escape sequence
In C octal escape sequence is represented by \ followed by three octal digits. Note that one or two octal digits are also allowed. An octal sequence ends either ends after three octal digits following \ or when a digit after \ is not an octal digit.

Examples:




// program to show octal escape sequence
#include <stdio.h>
int main()
{
    char str[] = "31\01267";
    printf("%s", str);
    return 0;
}

Output:

31
67

If we look at the output then after 31 a newline character is printed and then 67 is printed. This is because \012 is interpreted as \n or new line character.Actually, \012 represents octal escape sequence for \n or newline. Octal value of 12 in decimal is 10 and in ASCII it represents newline.




// program to show octal escape sequence
#include <stdio.h>
int main()
{
    char str[] = "31\12367";
    printf("%s", str);
    printf("\n");
    char str2[] = "11\77967";
    printf("%s", str2);
    return 0;
}

Output:

31S67
11?967

In str \123 is interpreted as octal escape sequence and value of octal 123 is 83 and character corresponding to it in my machine is ‘S’ as my machine uses ASCII. It can be different if character set used is not ASCII.
In str2 \77 is interpreted as an octal escape sequence and not \779. So, the value of 77 is 63 in decimal and in ASCII it is ‘?’.

This article is contributed by Ashish Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!