-1

I'm trying to understand this function and convert it to ctypes:

15 XDisplay* GetXDisplay() {
16   static XDisplay* display = NULL;
17   if (!display)
18     display = OpenNewXDisplay();
19   return display;
20 }

We see here if(!display) then do display = OpenNewXDisplay(); but what confuses me is the guy defines on the line above it that display is NULL (static XDisplay* display = NULL;) so why on earth the need for the if, if he just set it to null? Is display a global variable somehow?

glglgl
  • 89,107
  • 13
  • 149
  • 217
Noitidart
  • 35,443
  • 37
  • 154
  • 323
  • 3
    you should read more about whats static is – antonpuz Dec 22 '14 at 11:57
  • 2
    possible duplicate of [What does "static" mean in a C program?](http://stackoverflow.com/questions/572547/what-does-static-mean-in-a-c-program) – Jongware Dec 22 '14 at 11:58
  • Can you please help understand static in the context of this snipet, ill try to read right now, but if you can share some words I would be real greatful! :) – Noitidart Dec 22 '14 at 11:58

3 Answers3

5

display is a static variable.

For a static variable, initialisation only happens once, not every time the function is entered. This is just basic C (also basic C++, or basic Objective-C).

So this code is just a primitive way to create a singleton object.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • Thanks very much for helping me understand static in the context of my snippet!! :) Those are the best learning :) – Noitidart Dec 22 '14 at 11:59
1

You should read more about whats static word means:

http://en.wikipedia.org/wiki/Static_variable

basicly it means that the variable will be defined only once. which means that on the next time the function will be called the previous value of the variable will be stay.

So its not quite a global variable since its has the scope of a regular variable but keeps its value over function calls.

antonpuz
  • 3,256
  • 4
  • 25
  • 48
1

As the others mentioned before display is a static variable.

The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.

Source: http://www.tutorialspoint.com/cprogramming/c_storage_classes.htm

Eryk Sun
  • 33,190
  • 5
  • 92
  • 111
SVN
  • 254
  • 1
  • 2
  • 6