Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean when a numeric constant in C/C++ is prefixed with a 0?

Ok... So I had a silly idea and tried putting the value 0123 into an int, just curious to see what would happen, I assumed that when I printed the value I'd get 123, but instead I got 83... Any ideas why? what happens inside the compiler/memory that makes this value become 83?

I tried this in C++ and C with GCC compiler and also tried with a float which yielded the same results.

like image 501
CurtisJC Avatar asked Jun 15 '11 23:06

CurtisJC


People also ask

What is a numeric constant in C?

A numeric constant consists of numerals, an optional leading sign, and an optional decimal point. Examples of valid numeric constants are: 5.0, 6, -5. Examples of invalid numeric constants are: 1-, 1A, 3.. 4. Numeric constants have a maximum length of 20 characters.

What are the 3 types of constants?

Character constants, real constants, and integer constants, etc., are types of primary constants.

How are integer constants represented C?

Integer constant in C is a data type that is represented by const int . const int is capable of storing an integer in decimal, octal, and hexadecimal bases. The value to const int is assigned only when it is declared and cannot be changed afterward.

What is octal constant in C?

The C Standard defines octal constants as a 0 followed by octal digits (0 1 2 3 4 5 6 7). Programming errors can occur when decimal values are mistakenly specified as octal constants.


3 Answers

In C/C++ a numeric literal prefixed with a '0' is octal (base 8).

See http://www.cplusplus.com/doc/tutorial/constants/

like image 120
Richard Schneider Avatar answered Sep 21 '22 13:09

Richard Schneider


Congratulations! You've discovered octal.

like image 40
Peter K. Avatar answered Sep 18 '22 13:09

Peter K.


This is because any number starting with 0 like this is considered to be in octal (base 8) not decimal.

Same thing if you start with 0x you will get hexadecimal

like image 44
Locksfree Avatar answered Sep 19 '22 13:09

Locksfree