Thread: help again please sorry?

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    142

    help again please sorry?

    i just need to see if i'm getting things right.

    a local veriable is one that can only be used inside a single funtion but a globel variable can be used inside all functions.
    if this is true how do you declare globel variables
    WhAtHA hell Is GoInG ON

  2. #2
    Unregistered User
    Join Date
    Sep 2005
    Location
    Antarctica
    Posts
    341
    declare the varible outside of a function....

    Code:
    int this_is_global = 1;
    
    void myFunc()
    {
        int this_is_local = 2;
    }

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    847
    Thats correct. You declare global variables either in a header file (.h) which would be included by all source files that need to access the global variable or in the source file but not inside any function.

  4. #4
    Unregistered User
    Join Date
    Sep 2005
    Location
    Antarctica
    Posts
    341
    well, if you declare it in a header file, it will need to be given the keyword extern and will still need to be declared somewhere else. If you don't do this, the linker will get a conflict when more than 1 file includes the header.

  5. #5
    Registered User
    Join Date
    Sep 2005
    Posts
    142
    should this work or am i getting the whole concept wrong?

    Code:
    #include <iostream>
    
    using namespace std;
    
    inline void b() {
    
    	cout<< a <<endl;
    	cin.get();
    
    }
    
    int a;
    
    int main () {
    
    	cout<<"number";
    	cin>> a;
    	cin.get();
    	cout<< a <<endl;
    	cin.get();
    	b();
    
    }
    WhAtHA hell Is GoInG ON

  6. #6
    Registered User
    Join Date
    Sep 2005
    Posts
    142
    sorry i just worked it out you have to declare it before the function you wish to use it on
    WhAtHA hell Is GoInG ON

  7. #7
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    This won't compile
    Code:
    inline void b() {
    
    	cout<< a <<endl;
    	cin.get();
    
    }
    
    int a;
    But this will
    Code:
    int a;
    
    inline void b() {
    
    	cout<< a <<endl;
    	cin.get();
    
    }
    You have to declare global variables before their first use.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed