Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

variables - C++ int with preceding 0 changes entire value

I have this very strange problem where if I declare an int like so

int time = 0110;

and then display it to the console the value returned is 72. However when I remove the 0 at the front so that int time = 110; the console then displays 110 like expected.

Two things I'd like to know, first of all why it does this with a preceding 0 at the start of the int and is there a way to stop it so that 0110 at least equals 110?
Secondly is there any way to keep it so that 0110 returns 0110?
If you take a crack guess at the variable name I'm trying to do operations with 24hr time, but at this point any time before 1000 is causing problems because of this.

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

An integer literal that starts from 0 defines an octal integer literal. Now in C++ there are four categories of integer literals

integer-literal:
    decimal-literal integer-suffixopt
    octal-literal integer-suffixopt
    hexadecimal-literal integer-suffixopt
    binary-literal integer-suffixopt

And octal-integer literal is defined the following way

octal-literal:
    0 octal-literal
    opt octal-digit

That is it starts from 0.

Thus this octal integer literal

0110

corresponds to the following decimal number

8^2 + 8^1 

that is equal to 72.

You can be sure that 72 in octal representation is equivalent to 110 by running the following simple program

#include <iostream>
#include <iomanip>

int main() 
{
    std::cout << std::oct << 72 << std::endl;

    return 0;
}

The output is

110

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...