Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is scientific notation safe for integer constants in C?

Tags:

c++

c

gcc

For a while, I've been representing large powers of 10 in constants using scientific notation, just so I don't have to count the zeros. e.g.

#define DELAY_USEC 1e6 

A colleague pointed out that this isn't safe, because it's not an integer and is not guaranteed to always equal 1000000 exactly. Documentation seems to confirm this, but I'm wondering if its true in practicality. Is there any way to safely declare a power-of-ten integer using a shorthand? Is it safe just to cast it to an int in the define?

like image 971
David Dombrowsky Avatar asked Jun 24 '14 14:06

David Dombrowsky


People also ask

Can an integer be in scientific notation?

Scientific notation follows a very specific format in which a number is expressed as the product of a number greater than or equal to and less than , and a power of . The format is written , where and is an integer.

Can you use scientific notation in C?

Use %E Format Specifier to Print Numbers in Scientific Notation. Scientific notation for numbers is widely used to represent huge and small values with concise universal form. Namely, each number is represented with a single before the decimal point and power of 10s.

Which is valid integer constant in C?

Integer Constants An integer constant can be both negative or positive. We assume an integer constant to be positive if there is no sign in front of that constant. The allowable range for this type of constant is from -32768 to 32767.

How will you declare an integer constant in C language?

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.


1 Answers

In theory, no. Neither language specifies how floating point values are represented, or which values can be represented exactly. (UPDATE: apparently, C11 does recommend a representation. C++, and older C dialects, don't).

In practice, yes, for quite a large range of values. Any implementation you're remotely likely to encounter will use a 64-bit IEEE representation for double. This can represent any integer value up to 253 (approximately 9x1015) exactly. It can certainly represent anything representable by a 32-bit integer type.

like image 174
Mike Seymour Avatar answered Sep 19 '22 19:09

Mike Seymour