Do temp variables slow down my program?

A modern optimizing compiler should optimize those variables away, for example if we use the following example in godbolt with gcc using the -std=c99 -O3 flags (see it live):

#include <stdio.h>

void func()
{
  int i = 5;
  int j = 10;
  int result = i + j;

  printf( "%d\n", result ) ;
}

it will result in the following assembly:

movl    $15, %esi

for the calculation of i + j, this is form of constant propagation.

Note, I added the printf so that we have a side effect, otherwise func would have been optimized away to:

func:
  rep ret

These optimizations are allowed under the as-if rule, which only requires the compiler to emulate the observable behavior of a program. This is covered in the draft C99 standard section 5.1.2.3 Program execution which says:

In the abstract machine, all expressions are evaluated as specified by
the semantics. An actual implementation need not evaluate part of an
expression if it can deduce that its value is not used and that no
needed side effects are produced (including any caused by calling a
function or accessing a volatile object).

Also see: Optimizing C++ Code : Constant-Folding

Leave a Comment