20101004 - MSVC Optimizing Static Constant Function Tables?


Nope. Would be nice if the MSVC compiler could optimize FunctionJump() like FunctionIf() below,

#include <stdio.h>

typedef void (*Function)(const int);

static __forceinline void FunctionA(const int input) { printf("a=%d\n", input); }
static __forceinline void FunctionB(const int input) { printf("b=%d\n", input); }

static const Function function[2] = { FunctionA, FunctionB };

static __forceinline void FunctionJump(const int input) { function[input](input); }

static __forceinline void FunctionIf(const int input) {
if(input == 0) FunctionA(input);
if(input == 1) FunctionB(input); }

void main(void) {
FunctionJump(0);
FunctionJump(1);
FunctionIf(0);
FunctionIf(1); }


Trimmed section from assembly output /FAs,

PUBLIC _main
; Function compile flags: /Ogtpy
_TEXT SEGMENT
_main PROC

; 17 : FunctionJump(0);

push 0
call DWORD PTR _function

; 18 : FunctionJump(1);

push 1
call DWORD PTR _function+4

; 19 : FunctionIf(0);

push 0
push OFFSET $SG3833
call _printf

; 20 : FunctionIf(1); }

push 1
push OFFSET $SG3837
call _printf
add esp, 24 ; 00000018H
xor eax, eax
ret 0
_main ENDP