Using variable in function.

Mar 2, 2011 at 6:02pm
Is there any way to use a variable in a function? Say for example:
1
2
3
4
5
6
7
8
9
10
11
12
13
int function(int a,int b)
{
    int a1;
    a1=a-b;
    return(a1);
}

int main()
{
int a2;
cin >> a2;
int function(a2, 5);
}


Note this is not what I am trying to do, just an quick example.

EDIT: Edited errors. Also my question is how to make similiar thing to work?
Last edited on Mar 2, 2011 at 6:04pm
Mar 2, 2011 at 6:07pm
Yes. Your example works fine, only the temporary variable is unnecessary. However it is valid.

If I remember correctly: the a1 variable is allocated, you do whatever the heck you want with it, then a copy of the int is returned while that int that you just made dies along with the functions temporary memory.

What kind of similar things?
Mar 2, 2011 at 6:11pm
Well when I put up that example, compiler says:
initializer expression list treated as compound expression
Mar 2, 2011 at 6:18pm
line 12 should be int x = function(a2, 5); // Note that x =
Mar 2, 2011 at 6:21pm
Thanks!
Topic archived. No new replies allowed.