C ++ cout output description please

Possible duplicate:
Why initialize an integer in VC ++ to 010, other than initializing it to 10?

This confused me very much, and I hope that one of you will answer my question. How is it that this code will produce the result "116"?

#include <iostream> int main() { std::cout << 0164 << std::endl; return 0; } 

The code was compiled with MSVC ++ 2010 and g ++ under Mac OS X. "cout" can only print "0" and "164", but as soon as "0" is the first digit in the number that changes on the output.

+4
source share
2 answers

Since the 0 in front makes the number interpreted as octal .

 0164 = 4 * 1 + 6 * 8 + 1 * 64 = 116 

Or via binary:

  0164 = 0 1 6 4 = 000 001 110 100 = 1110100 = 116 

The same applies to hexadecimal numbers , you write them like for example 0x1FA.

+12
source

In C and his brothers, the number with 0 on the front is octal, not decimal.

Therefore, your number is 1 * 8 2 (1 * 64 = 64) plus 6 * 8 1 (6 * 8 = 48) plus 4 * 8 0 (4 * 1 = 4) , which is 116 .

See here for a great treatise on which hexadecimal and octal are in C.

+2
source

Source: https://habr.com/ru/post/1393494/


All Articles