Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC changes less than to less than or equal to

Tags:

c

gcc

assembly

gdb

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.

like image 733
pwaring Avatar asked Mar 30 '13 11:03

pwaring


2 Answers

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.

like image 135
Femaref Avatar answered Oct 17 '22 07:10

Femaref


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.

like image 39
Alok Save Avatar answered Oct 17 '22 07:10

Alok Save