There should not be any difference, but be an additional empirical (anal?) I tested this with g ++, creating a function for each of the code snippets. With and without optimization, it generated identical code no matter where the int a declaration is located.
#include <iostream> int variant_a(int b) { int a; while(b > 0) { a = b % 3; b /= 3; } return b; } int variant_b(int b) { while(b > 0) { int a = b % 3; b /= 3; } return b; } int main() { std::cout << variant_a(42) << std::endl; std::cout << variant_b(42) << std::endl; }
This is an unoptimized loop:
_Z9variant_ai: .LFB952: pushl %ebp .LCFI0: movl %esp, %ebp .LCFI1: subl $24, %esp .LCFI2: jmp .L2 .L3: movl 8(%ebp), %eax movl %eax, -20(%ebp) movl $1431655766, -24(%ebp) movl -24(%ebp), %eax imull -20(%ebp) movl %edx, %ecx movl -20(%ebp), %eax sarl $31, %eax subl %eax, %ecx movl %ecx, %eax addl %eax, %eax addl %ecx, %eax movl -20(%ebp), %edx subl %eax, %edx movl %edx, %eax movl %eax, -4(%ebp) movl 8(%ebp), %eax movl %eax, -20(%ebp) movl $1431655766, -24(%ebp) movl -24(%ebp), %eax imull -20(%ebp) movl %edx, %ecx movl -20(%ebp), %eax sarl $31, %eax movl %ecx, %edx subl %eax, %edx movl %edx, %eax movl %eax, 8(%ebp) .L2: cmpl $0, 8(%ebp) jg .L3 movl 8(%ebp), %eax leave ret
and optimized:
_Z9variant_ai: .LFB968: pushl %ebp .LCFI0: movl %esp, %ebp .LCFI1: pushl %ebx .LCFI2: movl 8(%ebp), %ebx testl %ebx, %ebx jle .L2 movl $1431655766, %ecx .p2align 4,,7 .p2align 3 .L5: movl %ebx, %eax imull %ecx movl %ebx, %eax sarl $31, %eax movl %edx, %ebx subl %eax, %ebx jne .L5 .L2: movl %ebx, %eax popl %ebx popl %ebp ret