What does “static” mean in C?

Questions : What does “static” mean in C?

I’ve seen the word static used in different places in C code; is this like a static function/class in C# (where the implementation is shared across objects)?

Total Answers: 20 Answers 20


Popular Answers:

    1. A static variable inside a function keeps its value between invocations.
    2. A static global variable or a function is “seen” only in the file it’s declared in

    (1) is the more foreign topic if you’re a newbie, so here’s an example:

    #include <stdio.h> void foo() { int a = 10; static int sa = 10; a += 5; sa += 5; printf("a = %d, sa = %dn", a, sa); } int main() { int i; for (i = 0; i < 10; ++i) foo(); } 

    This prints:

    a = 15, sa = 15 a = 15, sa = 20 a = 15, sa = 25 a = 15, sa = 30 a = 15, sa = 35 a = 15, sa = 40 a = 15, sa = 45 a = 15, sa = 50 a = 15, sa = 55 a = 15, sa = 60 

    This is useful for cases where a function needs to keep some state between invocations, and you don’t want to use global variables. Beware, however, this feature should be used very sparingly – it makes your code not thread-safe and harder to understand.

    (2) Is used widely as an “access control” feature. If you have a .c file implementing some functionality, it usually exposes only a few “public” functions to users. The rest of its functions should be made static, so that the user won’t be able to access them. This is encapsulation, a good practice.

    Quoting Wikipedia:

    In the C programming language, static is used with global variables and functions to set their scope to the containing file. In local variables, static is used to store the variable in the statically allocated memory instead of the automatically allocated memory. While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in data segment of the program at compile time, while the automatically allocated memory is normally implemented as a transient call stack.

    And to answer your second question, it’s not like in C#.

    In C++, however, static is also used to define class attributes (shared between all objects of the same class) and methods. In C there are no classes, so this feature is irrelevant.

  1. Short answer … it depends.

    1. Static defined local variables do not lose their value between function calls. In other words they are global variables, but scoped to the local function they are defined in.

    2. Static global variables are not visible outside of the C file they are defined in.

    3. Static functions are not visible outside of the C file they are defined in.

  2. It depends:

    int foo() { static int x; return ++x; } 

    The function would return 1, 2, 3, etc. — the variable is not on the stack.

    a.c:

    static int foo() { } 

    It means that this function has scope only in this file. So a.c and b.c can have different foo()s, and foo is not exposed to shared objects. So if you defined foo in a.c you couldn’t access it from b.c or from any other places.

    In most C libraries all “private” functions are static and most “public” are not.

  3. People keep saying that ‘static’ in C has two meanings. I offer an alternate way of viewing it that gives it a single meaning:

    • Applying ‘static’ to an item forces that item to have two properties: (a) It is not visible outside the current scope; (b) It is persistent.

    The reason it seems to have two meanings is that, in C, every item to which ‘static’ may be applied already has one of these two properties, so it seems as if that particular usage only involves the other.

    For example, consider variables. Variables declared outside of functions already have persistence (in the data segment), so applying ‘static’ can only make them not visible outside the current scope (compilation unit). Contrariwise, variables declared inside of functions already have non-visibility outside the current scope (function), so applying ‘static’ can only make them persistent.

    Applying ‘static’ to functions is just like applying it to global variables – code is necessarily persistent (at least within the language), so only visibility can be altered.

    NOTE: These comments only apply to C. In C++, applying ‘static’ to class methods is truly giving the keyword a different meaning. Similarly for the C99 array-argument extension.

  4. static means different things in different contexts.

    1. You can declare a static variable in a C function. This variable is only visible in the function however it behaves like a global in that it is only initialized once and it retains its value. In this example, everytime you call foo() it will print an increasing number. The static variable is initialized only once.

      void foo () { static int i = 0; printf("%d", i); i++ } 
    2. Another use of static is when you implement a function or global variable in a .c file but don’t want its symbol to be visible outside of the .obj generated by the file. e.g.

      static void foo() { ... } 
  5. From Wikipedia:

    In the C programming language, static is used with global variables and functions to set their scope to the containing file. In local variables, static is used to store the variable in the statically allocated memory instead of the automatically allocated memory. While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in data segment of the program at compile time, while the automatically allocated memory is normally implemented as a transient call stack.

  6. I hate to answer an old question, but I don’t think anybody has mentioned how K&R explain it in section A4.1 of “The C Programming Language”.

    In short, the word static is used with two meanings:

    1. Static is one of the two storage classes (the other being automatic). A static object keeps its value between invocations. The objects declared outside all blocks are always static and cannot be made automatic.
    2. But, when the static keyword (big emphasis on it being used in code as a keyword) is used with a declaration, it gives that object internal linkage so it can only be used within that translation unit. But if the keyword is used in a function, it changes the storage class of the object (the object would only be visible within that function anyway). The opposite of static is the extern keyword, which gives an object external linkage.

    Peter Van Der Linden gives these two meanings in “Expert C Programming”:

    • Inside a function, retains its value between calls.
    • At the function level, visible only in this file.
  7. If you declare a variable in a function static, its value will not be stored on the function call stack and will still be available when you call the function again.

    If you declare a global variable static, its scope will be restricted to within the file in which you declared it. This is slightly safer than a regular global which can be read and modified throughout your entire program.

  8. A static variable is a special variable that you can use in a function, and it saves the data between calls, and it does not delete it between calls. For example:

    void func(void) { static int count; // If you don't declare its value, it is initialized with zero printf("%d, ", count); ++count; } int main(void) { while(true) { func(); } return 0; } 

    The output:

    0, 1, 2, 3, 4, 5, …

  9. In C, static has two meanings, depending on scope of its use. In the global scope, when an object is declared at the file level, it means that that object is only visible within that file.

    At any other scope it declares an object that will retain its value between the different times that the particular scope is entered. For example, if an int is delcared within a procedure:

    void procedure(void) { static int i = 0; i++; } 

    the value of ‘i’ is initialized to zero on the first call to the procedure, and the value is retained each subsequent time the procedure is called. if ‘i’ were printed it would output a sequence of 0, 1, 2, 3, …

  10. If you declare this in a mytest.c file:

    static int my_variable; 

    Then this variable can only be seen from this file. The variable cannot be exported anywhere else.

    If you declare inside a function the value of the variable will keep its value each time the function is called.

    A static function cannot be exported from outside the file. So in a *.c file, you are hiding the functions and the variables if you declare them static.

  11. It is important to note that static variables in functions get initialized at the first entry into that function and persist even after their call has been finished; in case of recursive functions the static variable gets initialized only once and persists as well over all recursive calls and even after the call of the function has been finished.

    If the variable has been created outside a function, it means that the programmer is only able to use the variable in the source-file the variable has been declared.

  12. Static variables in C have the lifetime of the program.

    If defined in a function, they have local scope, i.e. they can be accessed only inside those functions. The value of static variables is preserved between function calls.

    For example:

    void function() { static int var = 1; var++; printf("%d", var); } int main() { function(); // Call 1 function(); // Call 2 } 

    In the above program, var is stored in the data segment. Its lifetime is the whole C program.

    After function call 1, var becomes 2. After function call 2, var becomes 3.

    The value of var is not destroyed between functions calls.

    If var had between non static and local variable, it would be stored in the stack segment in the C program. Since the stack frame of the function is destroyed after the function returns, the value of var is also destroyed.

    Initialized static variables are stored in the data segment of the C program whereas uninitialized ones are stored in the BSS segment.

    Another information about static: If a variable is global and static, it has the life time of the C program, but it has file scope. It is visible only in that file.

    To try this:

    file1.c

    static int x; int main() { printf("Accessing in same file%d", x): } 

    file2.c

     extern int x; func() { printf("accessing in different file %d",x); // Not allowed, x has the file scope of file1.c } run gcc -c file1.c gcc -c file2.c 

    Now try to link them using:

    gcc -o output file1.o file2.o 

    It would give a linker error as x has the file scope of file1.c and the linker would not be able to resolve the reference to variable x used in file2.c.

    References:

    1. http://en.wikipedia.org/wiki/Translation_unit_(programming)
    2. http://en.wikipedia.org/wiki/Call_stack
  13. A static variable value persists between different function calls andits scope is limited to the local block a static var always initializes with value 0

  14. There are 2 cases:

    (1) Local variables declared static: Allocated in data segment instead of stack. Its value retains when you call the function again.

    (2) Global variables or functions declared static: Invisible outside compilation unit (i.e. are local symbols in symbol table during linking).

  15. Static variables have a property of preserving their value even after they are out of their scope!Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.

    Look at this for example – A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over.

    #include<stdio.h>  int fun() { static int count = 0; count++; return count; } int main() { printf("%d ", fun()); printf("%d ", fun()); return 0; } 

    This will output: 1 2

    As 1 stays in the memory as it was declared static

    Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the below program, value of x is printed as 0, while value of y is something garbage. See this for more details.

    #include <stdio.h>  int main() { static int x; int y; printf("%d n %d", x, y); } 

    This will output : 0 [some_garbage_value]

    These are the major ones I found that weren’t explained above for a newbie!

  16. In C programming, static is a reserved keyword which controls both lifetime as well as visibility. If we declare a variable as static inside a function then it will only visible throughout that function. In this usage, this static variable’s lifetime will start when a function call and it will destroy after the execution of that function. you can see the following example:
  17. I didn’t see pyformat in the list so I thought I’d throw it in:

    console.log(pyformat( 'The {} {} jumped over the {}' , ['brown' ,'fox' ,'foobar'] )) console.log(pyformat('The {0} {1} jumped over the {1}' , ['brown' ,'fox' ,'foobar'] )) console.log(pyformat('The {color} {animal} jumped over the {thing}' , [] ,{color: 'brown' ,animal: 'fox' ,thing: 'foobaz'} )) 
  18. /** * Format string by replacing placeholders with value from element with * corresponsing index in `replacementArray`. * Replaces are made simultaneously, so that replacement values like * '{1}' will not mess up the function. * * Example 1: * ('{2} {1} {0}', ['three', 'two' ,'one']) -> 'one two three' * * Example 2: * ('{0}{1}', ['{1}', '{0}']) -> '{1}{0}' */ function stringFormat(formatString, replacementArray) { return formatString.replace( /{(d+)}/g, // Matches placeholders, e.g. '{1}' function formatStringReplacer(match, placeholderIndex) { // Convert String to Number placeholderIndex = Number(placeholderIndex); // Make sure that index is within replacement array bounds if (placeholderIndex < 0 || placeholderIndex > replacementArray.length - 1 ) { return placeholderIndex; } // Replace placeholder with value from replacement array return replacementArray[placeholderIndex]; } ); } 
  19. another suggestion is you use the string template:

    const getPathDadosCidades = (id: string) => `/clientes/${id}` const getPathDadosCidades = (id: string, role: string) => `/clientes/${id}/roles/${role}` 
  20. I did not see the String.format variant:

    String.format = function (string) { var args = Array.prototype.slice.call(arguments, 1, arguments.length); return string.replace(/{(d+)}/g, function (match, number) { return typeof args[number] != "undefined" ? args[number] : match; }); }; 
  21. String.prototype.format = function () { var formatted = this; for (var prop in arguments[0]) { var regexp = new RegExp('\{' + prop + '\}', 'gi'); formatted = formatted.replace(regexp, arguments[0][prop]); } return formatted; };
  22. With sprintf.js in place – one can make a nifty little format-thingy

    String.prototype.format = function(){ var _args = arguments Array.prototype.unshift.apply(_args,[this]) return sprintf.apply(undefined,_args) } // this gives you: "{%1$s}{%2$s}".format("1", "0") // {1}{0} 
  23. There is also Globalize.format in the jQuery Globalize project, the official globalization service for jQuery UI. IT’s nice when you need culture-aware formatting.

  24. I needed a function which could format a price (given in cents) in a way preferred by the user, and the tricky part is that the format is specified by the user — and I do not expect my users to understand printf-like syntax, or regexps, etc. My solution is somewhat similar to that used in Basic, so the user just marks with # places for digits, for example:

    simple_format(1234567,"$ ###,###,###.##") "$ 12,345.67" simple_format(1234567,"### ### ###,## pln") "12 345,67 pln" 

    I believe this is quite easy to understand by user, and quite easy to implement:

    function simple_format(integer,format){ var text = ""; for(var i=format.length;i--;){ if(format[i]=='#'){ text = (integer%10) + text; integer=Math.floor(integer/10); if(integer==0){ return format.substr(0,i).replace(/#(.*#)?/,"")+text; } }else{ text = format[i] + text; } } return text; } 
  25. arg function:

    /** * Qt stil arg() * var scr = "<div id='%1' class='%2'></div>".arg("mydiv").arg("mydivClass"); */ String.prototype.arg = function() { var signIndex = this.indexOf("%"); var result = this; if (signIndex > -1 && arguments.length > 0) { var argNumber = this.charAt(signIndex + 1); var _arg = "%"+argNumber; var argCount = this.split(_arg); for (var itemIndex = 0; itemIndex < argCount.length; itemIndex++) { result = result.replace(_arg, arguments[0]); } } return result; } 
  26. String.prototype.format = function(){ var final = String(this); for(let i=0; i<arguments.length;i++){ final = final.replace(`%s${i+1}`, arguments[i]) } return final || '' } console.log(("hello %s2 how %s3 you %s1").format('hi', 'hello', 'how'));
    <h1 id="text"> </h1>

  27. In typescript create a file named format.ts and import it whatever you need to use formatting.

    // contents of format.ts interface String { format(...args: any[]): string; } if (!String.prototype.format) { String.prototype.format = function() { let a = this; let b: any; // tslint:disable-next-line: forin for (b in arguments) { a = a.replace(/%[a-z]/, arguments[b]); } return a; }; } 

    To format string use this code:

    import './format'; console.log('Hello, %s!'.format('World')); 

    Example

    String.prototype.format = function() { let a = this; let b; for (b in arguments) { a = a.replace(/%[a-z]/, arguments[b]); } return a; }; console.log('Hello, %s!'.format('World'));

  28. if you just need to format a string with %s specifier only

    function _sprintf(message){ const regexp = RegExp('%s','g'); let match; let index = 1; while((match = regexp.exec(message)) !== null) { let replacement = arguments[index]; if (replacement) { let messageToArray = message.split(''); messageToArray.splice(match.index, regexp.lastIndex - match.index, replacement); message = messageToArray.join(''); index++; } else { break; } } return message; } _sprintf("my name is %s, my age is %s", "bob", 50); // my name is bob, my age is 50 
  29. Right now, there is a package called locutus which translate the functions of other languages to Javascript such as php, python, ruby etc.

    const printf = require('locutus/php/strings/printf') printf('Hello world'); 

    You can try this playground codesandbox

  30. Ok, so first we’ll set up some variables to use:

     const date = new Date(); const locale = 'en-us'; const wDay = date.toLocaleString(locale, {weekday: 'short'}); const month = date.toLocaleString(locale, {month: 'long'}); const year = date.toLocaleString(locale, {year: 'numeric'}); const minute = date.toLocaleString(locale, {minute: 'numeric'}); const [hour, ap] = date.toLocaleString(locale, {hour: 'numeric', hour12:true}).split(' '); let mDay = date.toLocaleString(locale, {day: 'numeric'}); switch(mDay % 10) { case 1: mDay += 'st'; break; case 2: mDay += 'nd'; break; case 3: mDay += 'rd'; break; default: mDay += 'th'; break; } 

    Now that we’ve got all that, we can format a string like so:

     const formatter = (...a) => `${a[0]}, the ${a[1]} of ${a[2]} ${a[3]} at ${a[4]}:${a[5]} ${a[6]}`; const formatted = formatter(wDay, mDay, month, year, hour, minute, ap); 

    We could even use named paramaters for the “formatter” function:

     const formatter = (wDay, mDay, month, year, hour, minute, ap) => `${wDay}, the ${mDay} of ${month} ${year} at ${hour}:${minute} ${ap}`; const formatted = formatter(wDay, mDay, month, year, hour, minute, ap); 

    If you’ll notice, the JS templates above are both the results of callbacks. If the entire piece of code above were encapsulated within a function that was expected to return a formatted date, it would not be hard to imagine how to construct an arbitrary “formatter” function in the same manner, that could be passed in from outside.

    tl;dr you can re-use template literals if you put them inside callbacks and use the args as the replacements.

  31. String.prototype.format = function format() { var msg = this; for(var i in arguments) msg = msg.replace(/{}/,arguments[i]).replace(new RegExp('\{'+i+'\}','g'),arguments[i]); return msg; }
  32. You can use this function

     String.prototype.format = function (args) { var str = this; return str.replace(String.prototype.format.regex, function(item) { var intVal = parseInt(item.substring(1, item.length - 1)); var replace; if (intVal >= 0) { replace = args[intVal]; } else if (intVal === -1) { replace = "{"; } else if (intVal === -2) { replace = "}"; } else { replace = ""; } return replace; }); }; String.prototype.format.regex = new RegExp("{-?[0-9]+}", "g"); // Sample usage. var str = "She {1} {0}{2} by the {0}{3}. {-1}^_^{-2}"; str = str.format(["sea", "sells", "shells", "shore"]); alert(str); 
  33. bobjs can do this:

    var sFormat = "My name is {0} and I am {1} years old."; var result = bob.string.formatString(sFormat, "Bob", 29); console.log(result); //output:  //==========  // My name is Bob and I am 29 years old.  
  34. String.prototype.repeat = function(n) { return new Array(++n).join(this); }; String.prototype.pad = function(requiredLength, paddingStr, paddingType) { var n = requiredLength - this.length; if (n) { paddingType = paddingType ? paddingType.toLowerCase() : ''; paddingStr = paddingStr || ' '; paddingStr = paddingStr.repeat( Math.ceil(n / paddingStr.length) ).substr(0, n); if (paddingType == 'both') { n /= 2; return paddingStr.substr( 0, Math.ceil(n) ) + this + paddingStr.substr( 0, Math.floor(n) ); } if (paddingType == 'left') { return paddingStr + this; } return this + paddingStr; } return this; }; // синтаксис аналогичен printf // 'Привет, %s!'.format('мир') -> "Привет, мир!" // '%.1s.%.1s. %s'.format('Иван', 'Иванович', 'Иванов') -> "И.И. Иванов" String.prototype.format = function() { var i = 0, params = arguments; return this.replace(/%(?:%|(?:(|[+-]+)(|0|'.+?)([1-9]d*)?(?:.([1-9]d*))?)?(s|d|f))/g, function(match, sign, padding, width, precision, type) { if (match == '%%') { return '%'; } var v = params[i++]; if (type == 'd') { v = Math.round(v); } else if (type == 'f') { v = v.toFixed(precision ? precision : 6); } if (/+/.test(sign) && v > 0) { v = '+' + v; } v += ''; if (type != 'f' && precision) { v = v.substr(0, precision); } if (width) { v = v.pad(width, padding == '' ? ' ' : padding[0] == "'" ? padding.substr(1) : padding, /-/.test(sign) ? 'right' : 'left'); } return v; }); }; // this.name = 'Вася'; // console.log( 'Привет, ${name}!'.template(this) ); // "Привет, Вася!" String.prototype.template = function(context) { return this.replace(/${(.*?)}/g, function(match, name) { return context[name]; }); };

Tasg: c, syntax