0

Hello, I'm wonder what static references are. Are they like:

static int number = 0;

I'm really confused. Thanks for any help.

4
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by Phil++
1

If you place a static variable inside a function lets say, it is declared once, and is only destructed once the program is closed. For example, try compiling this:

#include <iostream>
using namespace std;

// Returns the static variable 'total'
int addNum(int num) {
  static int total = 0;
  total += num;
  return total;
}

int main() {
  cout << addNum( 2 ) << '\n'; // outputs 2
  cout << addNum( 3 ) << '\n'; // outputs 5
  cout << addNum( 6 );         // outputs 11
  cin.ignore();
}

The example should be clear enough.

Edited by William Hemsworth: n/a

0

"Reference" has a very particular meaning in C++. It's not interchangable with the word "variable". I don't know whether you used the word "reference" as opposed to "variable" intentionally or not or if your question merely concerns the word "static". Here's a link on "reference".

http://en.wikipedia.org/wiki/Reference_(C%2B%2B)

"Static" means a couple of things, depending on how you use it. Thus the line you provided would have a different meaning depending on the context it's used in. Basically you have "static" as used with classes and "static" as used when you're not dealing with classes. You use them often for different purposes depending on whether you're using a class or not.

http://www.cprogramming.com/tutorial/statickeyword.html

Edited by VernonDozier: n/a

0

Do you know what a global variable is ?
Do you know what a local variable is ?

If so then read on.

Static variable is a mix between the two. Static variable has the same
lifetime as global, while its scope could be contained like a local variable.
Re-read William's classic total example, while thinking about the
statement above.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.