Hello,

i'm wondering if you can delcre a varible in int main and use it in a function?

eg

int main()
{
x = 7

cout << x<<endl;

return 0;
}

function --

{ ....blah blah

}

does something to x delcared in local scope (int main)

Or would I have to declare it globally?

Recommended Answers

All 4 Replies

Hello,

Sure can. Actually a good programming procedure. main() is a function, just like factorial(), or maybe openfile() or fillarray(). The thing that makes main special is that it is "called" first.

What you want to do is just fine. Local variables are the way to go!

Christian

Hello,

Sure can. Actually a good programming procedure. main() is a function, just like factorial(), or maybe openfile() or fillarray(). The thing that makes main special is that it is "called" first.

What you want to do is just fine. Local variables are the way to go!

Christian

just thought i'd try and make something to be more clearer:

#include <iostream>

int function int

using namespace std;

int main

{

int x = 5;
cout << "X before function <<x<<endl;


function()

return 0;

}

int function (int y)
{
int y;

y = x*x*x

cout << this is now the value of y << y;

}

however this should moan about int x not been defined ... :S

WHY NOT --> pass the variable to the function as a parameter!!!! then it will modify the variable as follows

#include <iostream>
using namespace std;

int function(int var)
{
    return (var * var * var);
}

int main(void)
{
    int x = 2; // our variable
    cout << "X before call " << x << "\n";
    x = function(x); // pass our x to the function, put result in x, alternative is to use pass by reference
    cout << "X after call " << x << "\n";
    return 0;
}

this program cubes the variable x and displays before/after results.
you can also use a call by reference method so that a function modifys the variables you pass into it (wheras I have just passed the variable and got a result, which i assign to the variable.....)

void function(int var)
{
    int result = var ^ 3;
    var = result;
} // change the function (it doesnt return anything, this probably is what you are after)
// calling it
function(&x); // sends x to the function. & means modify the x and keep the result in x

the problem you had before is that the X you are using in the function is NOT the global x as it is in a different statement block. using parameters in the functions is the best way to go, and the reference method is the easier method to use. Hope this helps :)

referencing is the same thing has pointers? If so i hate that way, but thers nothing better than practicing :D thanks for your help, most appricated

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.