Declaring int only once.

Just got in to a problem; how do you declare int just once, in the beginning of a program.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
int function(int a,int b)
{
   int something=10-b;
   return(something);
}

int main()
{
   int something=1; //Goal is this would be declared just one time.
   int x=function(something,2);
   cout << something; //Goal is that here it would print int returned from function.
}
Last edited on
You are setting the int you return to a variable 'x'.

Therefore to print out the returned int, change your cout so it is the following:

1
2
3
4
5
6
7
8
9
10
11
12
int function(int a,int b)
{
   int something=10-b;
   return(something);
}

int main()
{
   int something=1; //Goal is this would be declared just one time.
   int x=function(something,2);
   cout << x; //Goal is that here it would print int returned from function.
}




Your other problem is that your 'something' variable in the int main() gets passed to your function but not actually used. Therefore create a pointer within your main and pass the value by reference so that your code looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void function(int *a,int b)
{
   *a= *a-b;
}



int main()
{
   int something=1; //Goal is this would be declared just one time.
   function(&something,2);
   cout << something<<endl; //Goal is that here it would print int returned from function.

}




I think your aiming for the first code answer I gave, but the second shows how to change the something variable declared in the main without actually returning it.
Thank you.
Topic archived. No new replies allowed.