Integer and floating point math compiling inefficiencies??

Go To Last Post
6 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Below are two attempts at the same function.
The Modified version uses fewer bytes.

Why would it compile differently?

unsigned char A,C, j,k,z;
unsigned char B[] = {1,2,4};
float D, E, I, R;

Original:
R = ((float)(A-B[z])/(float)(A-C))*(D-E)+E

Modified:
j=(A-B[z]);
k=(A-C);
I= ((float)j / (float)k);
R = I*(D-E)+E;

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

A-B[z] and A-C are values of type "int".
j and k are values of type "unsigned char".

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

huh? A,C,B,j,k,z are all type unsigned char.

What am I missing?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

split63 wrote:
What am I missing?
Integer promotion. Yes, A and C are unsigned char. But to calculate A-C, the compiler has to promote both of them to "int".

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Quote:
Below are two attempts at the same function.
The Modified version uses fewer bytes.

Why would it compile differently?


Yes, single letter variables and aversion to whitespace characters will use fewer bytes of source code.

It makes no difference to the generated binary code.

Can you explain why you chose such random letters for your variables?

Historically, interpreted Microsoft Basic used less RAM storage for programs that omitted spaces and used meaningless names. Because the interpreter scanned less bytes, it ran slightly faster. Bear in mind that this applied to Home Computers of 40 years ago !

Perhaps people think the same applies to modern compiled languages. It does NOT.

David.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

As ezharkov said, because of the rules of integer promotion, the compiler will be forced to produce different code because you told it to do something different in the second example than the first. If you had started with unsigned ints instead of unsigned chars, and if you don't use the intermediate values anywhere else, then the optimizer may remove those variables and produce the same code for both examples.

Regards,
Steve A.

The Board helps those that help themselves.