I have coded a simple program in C++ on CODEBLOCK. the program is as follows:
#include <iostream>
using namespace std;
int main()
{
int num = 09; //ERROR: Invalid digit 9 in octal constant
cout << num << endl;
num = 08; //ERROR: Invalid digit 9 in octal constant
cout << num << endl;
return 0;
}
This code is same as the previous one. But i have changed value and wrote num=09 instead of 015.
I'm agree that if i initialize (int num = 015), it gives output in OCTAL that is 13.
But in the above program where i tried to initialize (int num = 09 and num = 08) it gives ERROR that you can see.
First of all, I wish to know why it generates an ERROR and how?
Second is what is the logic behind it?
Please give me logical reasons with suitable examples if any.
答案 0 :(得分:6)
Leading zeros cause integers to be interpreted as octal numbers in C/C++. 015 in octal is (1*8) + 5 = 13 in decimal.
答案 1 :(得分:0)
Constants in 8-base are defined that way. 158 = 1310.