C programming - functions when is it better to "return" results or just use a global?
twm47099
Posts: 867
The title says it all. I'm new at C programming, and for all of the functions I've written so far, I just transfer values in and out of the function using globals. I use locals inside of functions, but haven't used "return".
Can someone discuss the pros & cons?
Thanks
Tom
Can someone discuss the pros & cons?
Thanks
Tom
Comments
-Phil
Hmm. ;-0)
The other consideration is that "reentrant functions" (functions that can be used by multiple threads or cogs in propeller-speak) should stick to local (stack) variables. If globals are written and read by reentrant functions, they must be locked protected to maintain data integrity. Lock protection is expensive.
Void functions not returning a value (i.e. void fn()) can also modify parameters if any using pointers. Functions scanf or fread do that. Such functions do typically return something indicating success or failure though.
Using common names as global variables or function in separate files without using static to make them private can also cause problems.