user defined function

can i use this as a user defined function? or is there something wrong with it my debugged errors on it for some reason
(all int variables and defined in code)


int battle()
{
if (pick == 1 && cpu == 2)
return home++;
else if (pick == 1 && cpu == 3)
return comp++;
else if (pick == 2 && cpu == 1)
return comp++;
else if (pick == 2 && cpu == 3)
return home++;
else if (pick == 3 && cpu == 1)
return home++;
else if (pick == 3 && cpu == 2)
return comp++;
else if (pick = cpu)
return tie++;
}
Yes you can but you need to pass in the variables from the function like this (unless they are globally defined)

1
2
3
4
int battle(int pick, int cpu)
{
//... 
}


also include a function prototype if the function is not defined before the main function.

To create a function prototype just type in a line outside and before of the main statement like this
1
2
3
4
5
6
7
#include // your includes

int battle(int pick, int cpu);

int main()
{
}

The semicolon must be after your function prototype. The format for a prototype is this
RETURN_VALUE FUNCTION_NAME(FUNCTION ARGS);
Last edited on
FYI: doing that will NOT actually edit the values that you have passed. I.e.:

1
2
3
4
5
6
7
8
9
int do(int something) {
   return something++;
}

int main() {
   int stuff = 2;
   int stuff2 = do(stuff);
   //stuff == 2, stuff2 == 3
}


If you want to edit the values actually, then you will have to pass either a pointer to the int (int*) or a reference to the variable (&stuff).
Topic archived. No new replies allowed.