help

Started by
2 comments, last by RaistlinMajere 20 years, 5 months ago
How do i get it so my variable..lets call it "int a" can be used in main and in..."function b".
-----------------------------------------------------------"Shut up and eat your cheese sandwhich"
Advertisement
One way, obviously, is to make it global:


// main.cpp

int a=0;

int b()
{
return(a++);
}


int main()
{
int c;
c=b();
}



In this case, a is visible to any function in this source file. If function b() is defined in another file, you must use the extern keyword at the top of that file to let the compiler know that a is defined globally elsewhere:

// functionb.cpp

extern int a;

int b()
{
return (a++);
}


You can also pass a as a pointer (C or C++) or a reference (C++ only) to function b(), which can dereference the pointer and access a that way.

// functionb.c

int b(int *a)
{
return (*a)++;
}

// functionb.cpp
int b(int& a)
{
return (a++);
}

In the first case, you call function b as:

int c;
c=b(&a);

in order to hand it the pointer (address) to a. In the second case, you call b normally:

int c;
c=b(a);

and the compiler automatically handles the behind-the-scenes stuff that goes on when you pass by reference. Passing by reference is similar to passing by pointer, without the extra de-referencing over head.


Josh
vertexnormal AT linuxmail DOT org

Check out Golem: Lands of Shadow, an isometrically rendered hack-and-slash inspired equally by Nethack and Diablo.
If I understand your question then just call it outside the function

int a =0;void somefunc(){ a = 10;}int main(){ a= 20; somefunc(); cout<<a<<endl; return 0;}


that makes a global to both main, and somefun.
oh ok, thanks guys!
-----------------------------------------------------------"Shut up and eat your cheese sandwhich"

This topic is closed to new replies.

Advertisement