简体   繁体   中英

Does C have to calculate out a number in scientific notation?

The max value of a float is 3.40282347E+38. This is equivalent to 3.40282347 * 10^38. I am wondering if I set a float equal to this, does it have to actually perform the power and multiplication to get the value to store, or is scientific notation simply the actual value?

I am writing a school project in which we are optimizing as best we can, so this is relevant to me, especially since it is within a nested loop structure.

When you use literals in your source code, those literals (and mostly expression containing all literals for constant folding) are evaluated at compile time and converted to instructions like move immediate , add immediate , move special_constant_register etc.

For ex:

int a = 10, b = 0xA;

Here both 10 and 0xA literals are evaluated to same value at compile time. In your case also, double literal or float literal would be evaluated at compile time and most appropriate value would be assigned to the variable.

When you write 3.4e38 , it is completely evaluated at compile-time.

When you write 3.4 * 10^38 , you get a completely unexpected result. This is because ^ does not mean power-of in C. It means “exclusive or”, and 10 ^ 38 == 44 . Or maybe it doesn't compile at all, because it is evaluated as (3.4 * 10) ^ 38 , and xor is not defined for floating points. Or it is defined, so it would be 340 ^ 10 .

It's all done at compile time. The following code...

#include <float.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
  float foo = 3.40282347E+38;
  float bar = 3.40282347e38;
  printf("foo=%g\nbar=%g\n", foo, bar);
  return 0;
}

Produces this in assembler. To get the assembler use the -S flag to gcc ie, something like

gcc -S -Wall -O3 -pedantic -std=c11 scientific_notation.c 

This is using clang. I'll snip the assembler a bit...

 .section  __TEXT,__text,regular,pure_instructions
  .macosx_version_min 10, 11
  .section  __TEXT,__literal8,8byte_literals
  .align  3
LCPI0_0:
  .quad 5183643170566569984     ## double 3.4028234663852886E+38
  .section  __TEXT,__text,regular,pure_instructions
  .globl  _main
  .align  4, 0x90

...snipped.

Note this line .quad 5183643170566569984 . It's a constant. Also note that even though I have two of these constants in my code only one is needed by the compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM