Ok, first off. With the code as it stands now, you won't be able to use the int a
anywhere, except in the main
function, since it's a local variable to that function.
Either pass it as an argument, or declare it as a global (and an extern for that matter). Either way, I'd opt to pass it as an argument, if a
will be changed by the function explore
, you can do 1 of 2 things:
int explore( int val)
{
//do stuff
return new_val;
}
//call:
a = explore(a);//assigns return int to a
Or, if the returned int signals a status of some kind, pass a pointer to a
. This may, if you're new to pointers, seem like a sure way to over-complicate things, but it's very common, and very useful (added note on why this is useful to the bottom):
int explore(int *val)
{
*val += 123;//add 123 to val's value
//this is NOT the same as val += 123, because that's shifting the pointer!
return 0;
}
//call:
int return_val = explore(&a);//pass &[address-of]a
Now, linking two source files is easy, but you say you're using a header file, all well and good, but you don't seem to be including it anywhere, nor are you showing what it looks like. I suspect you're having trouble compiling your code... if so, show us what you've tried (how you're compiling the code), and what errors you're getting.
If you need a basic example of how to manually link 2 source files: Here's a previous answer of mine that shows, step by step, how to link 2 files
Why pointers?:
Many reasons, really. Here's just a few:
- limit memory usage: If you're passing big structs by value all over the place (ie, copying the same data over and over), your code will be slow, and your stack might end up cluttered with the same value. (recursion induced stack overflow)
- C can allocate heap memory, which can only be accessed through pointers, you can't turn a pointer variable into a non-pointer.
- Return values are often ways to notify you of an error that may have occurred.
The last point is crucial. If you're passing a
to explore
for some complex computation, changing the value of a
along the way. If, half way down the function, something goes pear-shaped, how do you notify the caller that the value of a
is no longer reliable? Simple:
int complex_function( int *val)
{
_Bool negative = *val > 0 ? false : true;
//do all sorts of magic stuff
//val wasn't negative, but is now, possible maxed int?
if (negative == false && *val < 0) return -1;//notify using -1
return 0;//usually, 0 means everything went well ok
}
//call like so:
if ((complex_function(&a)) != 0) exit( EXIT_FAILURE);//it's all gone wrong
//else, continue
Now that's where pointers are very useful. It doesn't require you to mess about with all too many temp variables, creating copies of values all over the place, and compare those to get to the same conclusion.