Returning extra results from a function in C
Archive - Originally posted on "The Horse's Mouth" - 2012-05-03 23:21:56 - Graham EllisThere are three ways of returning a result from a function in C. You can use return to pass a result back, you can use a variable declared outside all of your function (so it's global and accessible everywhere), and you can pass in a pointer to act at the target for where a result is to be saved.
If you've only one result to pass back, use the return. It's much the easiest, and it's what users will expect.
You should use variables declared outside your functions very sparingly - they're liable to leave code maintainers coming to look after the programs later on scratching their heads, and they make the name you use a universal one withing your whole program, which can be a bit of a problem if you want to use a library that someone's provided to you as a binary that happens to use the same name. I'm not saying "never", but please be careful.
So what's this pointer business?
• Set up a variable - in my example I'll call it doggie.
• Pass in the ADDRESS of doggie to your function.
• Store the (secondary) result in your function at the ADDRESS that's been passed in.
Although the address held in the function is a copy of the address in the main code, both the variables point to the same underlying variable / memory location, so changing *dd in the function also changes doggie in the main code.
Complete example [here]
A fourth alternative - outside the scope of my example which was written on last week's C course before I covered structures, is to pass back a structure or - better - a pointer to a structure.