What is the lifespan of an object?

In this example, what would be the difference if string_a declared as a static variable?

 const char *pString; void first(void) { const char string_a[] = " First string "; pString =(char *)string_a; } void second(void) { const char string_b[] = " Second string "; pString =(char *)string_b; } int main() { first(); second(); printf("%s\n", pString); } 
  • What determined the lifetime of an object in C?

  • What is the difference between global and file range of variables?

+4
source share
4 answers

There are two types of static : static in the global scope in the file and static inside the function.

The first declares an internal binding for the object, which means that it is available only inside the file. These objects are created in bss before entering main() . This memory area is always memset for all zeros until main() run.

The default value for objects created by an external functional area is global (external connection), that is, they can be accessed from other compilation units using the extern keyword.

static inside a function means that the object exists the first time the function is called before the program terminates.

Illustration:

 int external_linkage; static int internal_linkage; void foo() { static int static_in_function; } 

When the program starts, the value 0 guaranteed in all three variables, unlike the stack and heap variables.

+4
source

Static variables have file scope with internal linkage . This means that these variables cannot be accessed from other translation units.

Global variables also have file scope , but with external linkage . This means that these variables can be accessed from other translation units.

string_a is a local variable defined inside a function. If it is made as static, it will appear after the function is called and will exist until the program terminates (whereas non-static local variables will cease to exist as soon as the function ends).

+2
source

Global means that you can access this variable in another file using the extern keyword. The scope of the file means that this variable is not visible to other files. B c By default, each global variable has a global scope. If someone wants to make the global variable invisible to other files, they define a global variable with the static . static keyword converts the global scope to scope.

0
source

Static variables in functions are limited by scope. This means that these variables cannot be accessed from other functions, but unlike a local variable, it will not be destroyed after the scope and remains until the end of the program

Global variables have a file scope, but they are accessible from other files and are also provided
The extern keyword is used. static in the global scope in a file limits only the variable.

-one
source

Source: https://habr.com/ru/post/1491848/


All Articles