[TUT] The Use of Static Variables

For scripting examples for learning how to use AMXX.
User avatar
Archive-Poster
Posts: 1335
Gender:
United States of America

[TUT] The Use of Static Variables

Post by Archive-Poster »

What is a static variable? It is basically a global variable that can only be accessed by the function it is declared in.

This means that:

Code: Select all

#include <amxmodx>
#include <amxmisc>

public plugin_init()
{
    register_plugin("The Internet","Has","Spoken")
    
    fnDoFunc()
    iNum = 2
}

fnDoFunc()
{
    static iNum
    iNum = 1
}
Is NOT valid. Why? Because the static variable was declared in fnDoFunc, not plugin_init.

The example above does not exemplify the true power of static variables. If you're just going to zero it before you use it, use the operator "new". Declaring a new variable is not an expensive operation, simply the zeroing of it is.

But what can a static variable do?

Here's an example of the usage of a static variable vs. a new variable:

Static

Code: Select all

#include <amxmodx>
#include <amxmisc>

public plugin_init()
    register_plugin("The Internet","Has","Spoken")

public client_connect(id)
{
    static szName[33]
    
    get_user_name(id,szName,32)
    client_print(0,print_chat,"the matrix has %s",szName)
}
New

Code: Select all

#include <amxmodx>
#include <amxmisc>

public plugin_init()
    register_plugin("The Internet","Has","Spoken")

public client_connect(id)
{
    new szName[33]
    get_user_name(id,szName,32)
    client_print(0,print_chat,"the matrix has %s",szName)
}
But why is the static version faster? Because the memory isn't created every single time it's needed, rather it's left there, kind of like a global variable never loses its value ever after being used in a function.

So for example, take in this hypothetical sequence of events in a server:

Static

Code: Select all

  static variable initialized
  
  Hawk552 joins server
  client_connect called
  static variable already exists
  get name
  print name
  
  *5 minutes later*
  
  zomg joins server
  client_connect called
  static variable already exists with contents "Hawk552\0..."
  get name -> now looks like "zomg\052\0...", however it ends at the first \0 so the trailing 52 doesn't matter
  print name
New

Code: Select all

  Hawk552 joins server
   client_connect called
  new variable initialized
   get name
   print name
  
  *5 minutes later*
  
  zomg joins server
    client_connect called
   new variable initialized
    get name
    print name
And that is basically why static variables are useful.

Who is online

Users browsing this forum: No registered users and 1 guest