Search code examples
c++octal

Why zero at the beginning of int variable gives error?


#include <iostream>
using namespace std;
int main()
{
    struct information
    {
        string  name;
        string  bloodgroup;
        int     mobno;
    };

    information person1={"Ali Hamza","O-",434233434};
    information person2={"Akram Ali","B",034};
    cout << endl << person1.name << endl;
    cout << person1.bloodgroup << endl << person1.mobno<< endl;
    cout << endl << person2.name << endl << person2.bloodgroup << endl << person2.mobno<<endl;

    int num = 09;
    cout << num;

    return 0;
}

I wonder when I saw errors like invalid digit in octal constant 9 and 8.Also it print wrong value for the value of "mobno"(in structure) if zero is the first digit, but it give error when zero is used as first digit for num at the end of program.Is there someone who would explain it for me?


Solution

  • Starting an integer literal with 0 in C/C++ means that you intend for it to be interpreted in octal or base-8.

    So, for example, the number '034' is to be interpreted as 3*8^1 + 4*8^0 = 3*8 + 4*1 = 28. So it is equivalent to '28'.

    The integer literal '09' is invalid as '9' is not a digit in octal.