-4
class A
{
    static void f(void)
    {
        int a;
        static int b;
    }
};

Is there any (formal or practical) difference between a and b?

NPS
  • 6,003
  • 11
  • 53
  • 90
  • 1
    `b` will retain its value across calls, while `a` will be reinitialized every time... – dlf Nov 20 '14 at 20:16
  • 1
    http://en.cppreference.com/w/cpp/language/storage_duration – Anton Savin Nov 20 '14 at 20:17
  • 1
    What happened when you tried it? – Caleb Nov 20 '14 at 20:21
  • Yes, `a` is allocated on the stack, `b` is allocated in the data-section. The fact the the function is `static` does not effect the "behavior" of variables in it (i.e., would be the same for a non-static function). – barak manos Nov 20 '14 at 20:21

2 Answers2

4

Yes, consider the following:

#include <iostream>
using namespace std;

class A
{
    public:
    static void func()
    {
        static int a = 10;
        int b = 10;
        a++;
        b++;
        std::cout << a << " " << b << endl;
    }
};

int main() {
    A a, b;
    a.func();
    b.func();
    a.func();
    return 0;
}

a is shared across all instances of func, but b is local to each instance, so the output is:

11 11
12 11
13 11

http://ideone.com/kwlra3

IllusiveBrian
  • 3,105
  • 2
  • 14
  • 17
2

Yes both are different. For every call a will be created whereas b will be created only once and it is same for all the objects of type A. By same I mean, all the objects share a single memory of b.

Venkatesh
  • 1,537
  • 15
  • 28