0

sorry if this is a silly question, I am relatively new to C programming. Thus I have probably misunderstood something fundamental about variables/overflows.

I made this simple program and I can't explain the result

#include <stdio.h>
#include <math.h>
int main() {
  double number = pow(2, 1000);
  printf("%f\n", number);
}

The result of that (compiled with gcc) is a humongous number that should never fit in a variable of type double: 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376.000000

Usually when I try to assign a constant that is too large for it's type the compiler gives me an error.

So my question is: What is this number? Why am I not getting any errors? Is the variable number actually storing this value? Plainly, what's happening?

supah0t
  • 37
  • 5
  • 1
    there's nothing wrong with that. 2^1000 is ~1.07150860718627E+301 while the upper limit of double is 1.79769313486232E+308, so how can it not fit in double? – phuclv Jun 16 '21 at 15:01
  • 1
    duplicates: [`pow(2,1000)` is normaly to big for double, but it's working. why?](https://stackoverflow.com/q/7371928/995714), [Double precision `pow(2, 1000)`](https://stackoverflow.com/q/3389195/995714), [How can 8 bytes hold 302 decimal digits? (Euler challenge 16)](https://stackoverflow.com/q/14567127/995714) – phuclv Jun 16 '21 at 15:04
  • *"is a humongous number that should never fit in a variable of type double"* - What was your method to determine this? Were you just assuming that? – klutt Jun 16 '21 at 15:08

2 Answers2

1

Doubles are not stored like integers. This page explains how double are representated in memory

Doubles contain 1 byte of sign, 11 bits for the exponent and 53 bits for the sigificand precision. Thus you can store numbers up to 1.7*10^308. Thus, your number cand be represented in a double (although with a limited precision). When printing it with %f, you just get its numerical value (approximated).

Maxime B.
  • 1,116
  • 8
  • 21
0

In C, double type can fit more than 300 decimal digits! A double is stored in 8 bytes, holding a number in the range 2.3E-308 to 1.7E+308 (15 decimal places accuracy).

Reference: https://www.tutorialspoint.com/cprogramming/c_data_types.htm

Obsidian
  • 3,719
  • 8
  • 17
  • 30