Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - Local Variables

Node:Local variables, Next:, Previous:Global variables, Up:Scope



Local Variables

Local variables, on the other hand, are only visible within local scope. They are "trapped" inside their code blocks.

Just as global scope contains many functions, however, each function can contain many code blocks (defined with curly brackets: {...}). C allows blocks within blocks, even functions within functions, ad infinitum. A local variable is visible within its own block and the ones that block contains, but invisible outside its own block.

int a;

/* Global scope.  Global variable 'a' is visible here,
   but not local variables 'b' or 'c'. */

int main()
{
  int b;

  /* Local scope of 'main'.
     Variables 'a' and 'b' are visible here,
     but not 'c'. */

  {
    int c;

    /* Local scope of {...} block within 'main'.
       Variables 'a', 'b', and 'c' are all visible here. */
  }

  exit (0);
}

Local variables are not visible outside their curly brackets. To use an "existence" rather than a "visibility" metaphor, local variables are created when the opening brace is met, and they are destroyed when the closing brace is met. (Do not take this too literally; they are not created and destroyed in your C source code, but internally to the computer, when you run the program.)

 
 
  Published under free license. Design by Interspire