C - The static keyword

The example below demonstrates a static local variable and a static function

The function WriteLog() uses a static local variable. The variable lineNumber has function scope. It is initialized the first time the function is called and retains its value across calls.


The function WriteLog() calls a static function called LogInternal(). LogInternal is accessible within Logger.cpp only.


main.cpp


  int main()
  {
      WriteLog("hello");
      WriteLog("world");
  }
  

Logger.cpp


  #include "Logger.h"
  
  void WriteLog(const char* message)
  {
      static int lineNumber = 0;
      
      LogInternal(lineNumber, message);
      
      lineNumber++;
  }
  
  static void LogInternal(int lineNumber, const char* message)
  {
      printf("%d: %s\r\n", lineNumber, message);
  }
  

Logger.h


  // public methods
  void WriteLog(const char* message);
  
  // implementation
  static void LogInternal(int lineNumber, const char* message);
  

The output:


  1: hello
  2: world
  

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath