Shop OBEX P1 Docs P2 Docs Learn Events
C programming - functions when is it better to "return" results or just use a global? — Parallax Forums

C programming - functions when is it better to "return" results or just use a global?

twm47099twm47099 Posts: 867
edited 2014-08-15 13:08 in Learn with BlocklyProp
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

Comments

  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2014-08-15 12:47
    My opinion is that it's better if any effects of the function call be obvious where the function is called in the program. That implies using a return instead of remotely assigning a value to a global, which is invisible in the call itself.

    -Phil
  • jazzedjazzed Posts: 11,803
    edited 2014-08-15 13:08
    I agree with 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.
Sign In or Register to comment.