mercredi 21 décembre 2016

static const cached result

In the following example -

#include <iostream>

int someMethod(){
  static int a = 20;
  static const int result = a + 1;
  ++a;
  std::cout << " [" << a << "] ";
  return result;
}

int main(){
  std::cout << someMethod() << "\n";
  std::cout << someMethod() << "\n";
  std::cout << someMethod() << "\n";
}

The output comes as -

[21] 21

[22] 21

[23] 21

What is the reason that is preventing result value to be modified on subsequent calls made to the same function? I've printed the output of variable a as well, which is certainly being incremented and since it is static as well there must not be multiple copies existing for the same method.

IDEONE - COMPILER OUTPUT

Aucun commentaire:

Enregistrer un commentaire