1

this is the code snippet

static chck()//tracking how many times main has been called
{
    static a=0;
    int y=0;//this is not supposed to work
    cout<<"Total time main has been called:  ";
    a++;
    return a;
}

our teacher told us that static functions can't change or create non static variables but it works for me ,why?

user3211362
  • 43
  • 1
  • 5
  • 2
    `static` **member** functions cannot use/change non-static **data members** because that makes no sense. The function isn't called on any object to use the members of. This `static` just means the function has internal linkage. It's completely different. – chris Jul 03 '14 at 16:56
  • what does a non member static function have linkage to? – user3211362 Jul 03 '14 at 16:58
  • Consider reading through http://stackoverflow.com/questions/1358400/what-is-external-linkage-and-internal-linkage-in-c – chris Jul 03 '14 at 17:07

2 Answers2

1

In this case "y" is a stack variable which this function can access.

The theory is static member functions (static Methods in a class) cannot access non static member variables (non static variables in the class) as there is no object as "this" inside a static member function.

Sujith Gunawardhane
  • 1,251
  • 1
  • 10
  • 24
0

static may well be the most overused keyword in c++. Your first use of it refers to the linkage of chck(), i.e. it has internal linkage. Your second use makes a static with respect to calls to ckch(), i.e. it's value will be preserved between calls. You are think of static member functions of a class that can't access non-static data members, i.e. those data members that are created per object instance.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54