Tutorial - C / C++ - Local variables


Coding Friends Tutorial Index - > C / C++

Author Ian - Tutorial Posts = 62
This is a tutorial about variable scope, a variable is a means to store data within the context of the program. For example, if you wish to store a numerical value then you would not store that number in a string, but within a integer or floating point number.

There are different types of variables, integer / string etc, but the scope of a variable is the area in which the variable is defined within block of code that it is situated.

This is some c++ code to demonstrate the difference between local variables and global.
---
#include <iostream>

// global variable
int value1 = 0;

void globalVariable()
{
       // output the global variable
       std::cout << "Global " << value1 << "\n";
}

int main(void)
{
       int value1 = 1;                     // local function variable
       globalVariable();              // output the global
       std::cout << "Local " << value1 << "\n";       // output the local
       
       // the value1 here is local to the for loop
       for (int value1 = 10; value1 < 15; value1++)
       {
              std::cout << "For loop : " << value1 << "\n";
       }
       
       // output the global and local and notice they have not changed with the very local for loop
       // with the same variable name.
       globalVariable();
       std::cout << "Local " << value1 << "\n";
       return 0;       
}
---
the output would be
---
Global 0
Local 1
For loop : 10
For loop : 11
For loop : 12
For loop : 13
For loop : 14
Global 0
Local 1
---
To demonstrate that the global /local and looping locals do only work within there area.
Creation of cool tutorials :)
User Name Password
Copyright@CodingFriends, 2005-2006. All Rights Reserved.
Home | Forums | Tutorials | Users
RSS Feeds - Global Global CodingFriends RSS Feed - Tutorials Tutorials CodingFriends RSS Feed - Forums Forums CodingFriends RSS Feed - News News CodingFriends RSS Feed
Users
Login|Password problem| Register here

Tutorials
Tutorials Home| C/C++| C#/Mono| Java| Javascript| PHP| Ruby| SQL| (X)HTML/CSS| VB| Linux| Windows

Forum
Forum Home

Projects
3D Game

Site
Home| About me| Links| FAQ

Search