Back to TILs

C++ variable_lifetime

Date: 2023-02-25Last modified: 2024-11-02

Table of contents

#define print_var(var) fmt::print( "{:>20} = {}\n", #var, var );

// static duration: dies when program ends
int static_var_1{80};

void some_function() {
  fmt::print( "\nsome_function()\n");
  // local (automatic) duration: dies at end of block
  int local_var_2{30};

  // static duration: dies when program ends
  static int static_var_3{40}; // the initialization occurs only one time
  print_var(static_var_3);
  ++static_var_3; // 41, 42, 43, ...

  // you decide when it dies
  int dynamic_var_4{50};

  print_var(local_var_2);
  print_var(static_var_3);
  print_var(dynamic_var_4);
}

int main([[maybe_unused]] int argc, [[maybe_unused]] char **argv) {
  print_var(static_var_1);
  some_function();
  some_function();
  some_function();
  return 0;
}

Possible output

        static_var_1 = 80

some_function()
        static_var_3 = 40
         local_var_2 = 30
        static_var_3 = 41
       dynamic_var_4 = 50

some_function()
        static_var_3 = 41
         local_var_2 = 30
        static_var_3 = 42
       dynamic_var_4 = 50

some_function()
        static_var_3 = 42
         local_var_2 = 30
        static_var_3 = 43
       dynamic_var_4 = 50

References