On 7/30/07, Siddhesh Poyarekar wrote:
On 7/30/07, Dinesh Joshi wrote:
How will it add an extra condition? The compiler is smart enough to understand while( true ) is an unconditional loop and will not generate the code for a condition check instead it'll just put a JMP instruction back to the start of the block. So no overheads there.
Exactly. So does this happen even with optimization turned off? If it does then shouldn't my code in query two cause a miss in the instruction pipeline all the time?
Again, we come to the implementation part. Depends on the processor on which you run the code on. It all depends on the branch prediction logic. But here branch prediction doesn't come into picture! The JMP instruction is an unconditional jump. Your code will generate assembly like this:
.file "test2.c" .text .globl main .type main, @function main: leal 4(%esp), %ecx andl $-16, %esp pushl -4(%ecx) pushl %ebp movl %esp, %ebp pushl %ecx subl $16, %esp .L2: addl $1, -8(%ebp) jmp .L2 .size main, .-main .ident "GCC: (GNU) 4.1.0 20060304 (Red Hat 4.1.0-3)" .section .note.GNU-stack,"",@progbits
See the unconditional JMP instruction that GCC generated?
The C source for this assembly is :
int main() { int i; while( 1 ) { i++; } return 0; }
Now get it ?