5

I have the following simple program that I'm using to refresh my memory of GDB (which I haven't touched for many years).

#include <stdio.h>

int main()
{
  int i;

  for (i = 0; i < 10; i++)
  {
    printf("Hello World\n");
  }

  return 0;
}

I compile this with gcc -g for-test.c -o for-test. Based on the man page, I don't expect any optimisations to be used, since I haven't specified any.

When I load this into GDB and run disassemble main, the i < 10 comparison generates the following:

cmp    DWORD PTR [rbp-0x4],0x9
jle    0x4004fe <main+10>

This seems to have effectively changed a comparison of i < 10 to i <= 9. Given that these are integer comparisons, there shouldn't be a difference, but I was wondering if there is any reason why GCC outputs this assembly, instead of comparing against 10 and jumping if less than (JL)?

Edit: This is on a machine with a 64-bit processor, running Ubuntu with GCC 4.6.3 and GDB 7.4-2012.04.

4

3 回答 3

5

There shouldn't be a difference in execution speed. I think gcc generally emits jle for such comparisions and does it for consistency in the generated assembly.

于 2013-03-30T11:44:17.493 回答
2

Compilers are allowed to perform optimizations as long as the observable behavior is same. This is known as the As-If rule. Since the observable behavior for both the cases is same, the compiler is allowed to generate the assembly code in either of the two. This is true even if you do not have any optimizations enabled.

于 2013-03-30T11:45:05.693 回答
0

It isn't effective optimization, just another way to write the same. Compiling with -O flag generates much more complex optimizations.

于 2013-03-30T11:39:39.457 回答