Author Topic: Function return in C  (Read 8193 times)

0 Members and 1 Guest are viewing this topic.

Offline danadak

  • Super Contributor
  • ***
  • Posts: 1875
  • Country: us
  • Reactor Operator SSN-583, Retired EE
Re: Function return in C
« Reply #25 on: August 21, 2017, 03:47:12 pm »
I am a C lightweight, but I found multiple exits allowed me to reduce un-necessary code execution,
overall, and give me a little more HP to apply to other stuff, like display processing. In fact I coded
the f() such that most frequent escapes occured early before other tests for exit. Or maybe I am a
lousy coder and took a non professional way out. But then we are writing books, pamphlets in some
cases, and styles vary....:)


Regards, Dana.
Love Cypress PSOC, ATTiny, Bit Slice, OpAmps, Oscilloscopes, and Analog Gurus like Pease, Miller, Widlar, Dobkin, obsessed with being an engineer
 

Offline Kjelt

  • Super Contributor
  • ***
  • Posts: 6460
  • Country: nl
Re: Function return in C
« Reply #26 on: August 21, 2017, 03:48:02 pm »
Quote
GOTO sometimes is useful to make the code more clean and readable.
I disagree, a goto can make code unreadable as the above example demonstrates it can reverse the logical program flow by jumping up , so logically back in the code.
It is as saying we are going to write from right to left instead of left to right, which some cultures do btw.
Code should flow from top to bottom, functions should be relatively short and easy to understand.
If something is an indicator for code that will generate errors in the future and is not maintainable it is code that is not easy to comprehend or readable.
Allowing a goto in your coding guidelines will have to be accompanied by more "don'ts" than "do's" , making it again harder to remember so best just to strike it completely IMO.
I never used it in the last 25 years so it is perfectly possible to live without :)
 

Offline Brumby

  • Supporter
  • ****
  • Posts: 12297
  • Country: au
Re: Function return in C
« Reply #27 on: August 21, 2017, 03:56:35 pm »
a goto can make code unreadable as the above example demonstrates it can reverse the logical program flow by jumping up , so logically back in the code.

Absolutely agree with that - which is why I would only ever use a goto in a forward jump.

Quote
I never used it in the last 25 years so it is perfectly possible to live without :)

I have to admit, I cannot remember when the last time I used a goto .....
 

Offline bd139

  • Super Contributor
  • ***
  • Posts: 23018
  • Country: gb
Re: Function return in C
« Reply #28 on: August 21, 2017, 04:04:57 pm »
Agree with using it as a forward jump only.

TBH in the 3 million lines of code in our main C# based project, we have three gotos and they are "goto case" in state machines. If this was C there would be a LOT more. So it depends on the language as much as the application.
 

Offline gnif

  • Administrator
  • *****
  • Posts: 1675
  • Country: au
Re: Function return in C
« Reply #29 on: August 21, 2017, 04:08:41 pm »
I have read in some articles that is recommended to have only one return point for a function rather than having return points at multiple locations.
Why is it so?? How does it make the debugging simple??

Suppose you want to put a breakpoint at the return point of a function. Where are you going to put the breakpoint if there are multiple returns? Suppose you want to trace the execution path through the code, so you log the function on entry and on exit. How will you do that if there are multiple exits?

In this instance I normally put the code into a while loop like so

Code: [Select]
int myFunc(void)
{
  while(1)
  {
    if (earlyExit)
      break;

    if (someOtherExit)
      break;

    return 1;
  }
  return 0;
}

 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11622
  • Country: my
  • reassessing directives...
Re: Function return in C
« Reply #30 on: August 21, 2017, 04:25:34 pm »
a goto can make code unreadable as the above example demonstrates it can reverse the logical program flow by jumping up , so logically back in the code.
Absolutely agree with that - which is why I would only ever use a goto in a forward jump.

Quote
I never used it in the last 25 years so it is perfectly possible to live without :)
I have to admit, I cannot remember when the last time I used a goto .....
when is the last time you use "if"? thats a forward jump... when is the last time you use "while" and "for"? thats the backward jump. except the language has made them a little bit organized for you ;)
Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 

Offline Kjelt

  • Super Contributor
  • ***
  • Posts: 6460
  • Country: nl
Re: Function return in C
« Reply #31 on: August 21, 2017, 05:11:22 pm »
when is the last time you use "if"? thats a forward jump... when is the last time you use "while" and "for"? thats the backward jump. except the language has made them a little bit organized for you ;) 
No that is called a "conditional loop", if  you were serious I would advise you to pick up your books again  :)
 

Offline glarsson

  • Frequent Contributor
  • **
  • Posts: 814
  • Country: se
Re: Function return in C
« Reply #32 on: August 21, 2017, 05:34:51 pm »
Code: [Select]
int myFunc(void)
{
  while(1)
  {
    if (earlyExit)
      break;

    if (someOtherExit)
      break;

    return 1;
  }
  return 0;
}
You tell the code maintainer that you have an infinite while loop, but then only use it once.
You have two ways to leave the infinite loop, break or return.
You still have more than one return.
You use break to implement a goto.
The goto-breaks will break (sic) if the code implementing the functionality of the function happens to use a switch, while or for.

This obfuscated code would never make it through code inspection where I work.
 
The following users thanked this post: newbrain

Offline KL27x

  • Super Contributor
  • ***
  • Posts: 4099
  • Country: us
Re: Function return in C
« Reply #33 on: August 21, 2017, 05:56:43 pm »
Quote
Quote
when is the last time you use "if"? thats a forward jump... when is the last time you use "while" and "for"? thats the backward jump. except the language has made them a little bit organized for you ;)



No that is called a "conditional loop", if  you were serious I would advise you to pick up your books again  :)
What do you think a backwards jump is used for, 99.99% of the time? Mechatrommer obviously does not need to be corrected. :) You do not need a book to know how to use a conditional loop or a backwards jump, and picking up a book to read the name is not going to teach you how to code. :) I think you're joking, because of the smiley, but it is hard to tell. :):) :)

**To make any kind of loop, the PC is jumping back in the machine code. If you want the code to execute only top to bottom, you have to redundantly add the same code over and over until you run out of space. lol.

In general, it is better to write code in such a structure that you CAN ignore some of the details and not get into trouble. But if you remove yourself so far from what is actually happening, you can end up in a situation where you CANNOT write code without following specific structure, because you have no clue what is actually happening. This might be the "best" way to write code for certain complicated project, but there are some things which you will not be able to do effectively/practically due to loss of efficiency and not enough speed and memory in the world to compensate. One should maybe try to remember how to ignore the rules without breaking the code, even if one rarely has to do it. And be conscientious to tidy up these potential sources of error where it does not matter one way or the other, even if you ARE 100% aware of how to write efficient and clear "bad/spaghetti" code, esp because one day you might have to support your own code and on this day you might not be as smart. I treat future me as pretty dumb. If you have a section of code with one entry, one exit, and documented with memory/stack usage, it has this advantage: no matter how complicated it is, even if you can't figure out how it works to save your life, because whoever wrote it (including past you) is smarter (or just has totally alien thought process and code style) than (present) you, you can more easily remove and rewrite the entire section without fucking up something else.
« Last Edit: August 21, 2017, 08:03:27 pm by KL27x »
 

Online IanB

  • Super Contributor
  • ***
  • Posts: 11859
  • Country: us
Re: Function return in C
« Reply #34 on: August 21, 2017, 06:05:03 pm »
While I support the preference to avoid using the goto, I do not exclude it completely.  BUT - I have some very simple guidelines for its use.  The first and foremost is that it is always used to branch to a forward point down the code.  Never backward.  The second is that it is not used in normal program logic - only for exception situations.

A third point would be not to jump inside a block from outside.
 

Offline alank2

  • Super Contributor
  • ***
  • Posts: 2185
Re: Function return in C
« Reply #35 on: August 21, 2017, 06:22:11 pm »
You guys are tough!  I remember being taught pascal where goto wasn't an option and it is hard to argue with the program flow that comes out of that.  I fully agree with you guys that an entire program written around goto is a disaster.  At the same time, I don't think loops are "the end all be all" either.  Sometimes loops are very counter intuitive to what you are trying to accomplish.  To force oneself to use them when they are not ideal - what good is that when it is just going to be compiled to a JMP anyway...
 

Offline bd139

  • Super Contributor
  • ***
  • Posts: 23018
  • Country: gb
Re: Function return in C
« Reply #36 on: August 21, 2017, 07:50:59 pm »
Hey I've written something quickly that will make you puke:

1. It uses a poor clone of pascal syntax simply because I hate pascal.
2. It's written entirely in ANSI C
3. It actually compiles and executes.
4. It implements goto but doesn't actually use goto therefore making this entire problem a non issue as you can hand over your compiler transcripts :D
5. It's just horrible.

Have fun  :-DD

Code: [Select]
#include <stdio.h>

#define begin int _u=0;while(1){switch(_u){default:
#define end }}
#define label(x) case(x):
#define goto(x) _u=x;break;
#define exitprogram return 0;
#define writeln(x) printf(x);
#define program int main(int argc, char *argv[]) {
#define endprogram }

program
    begin
        goto(010101101);
        label(011101101)
            writeln("Goto ");
            goto(001001101)
        label(011001101)
            writeln("EEVblog ");
            goto(011101101)
        label(001001101)
            writeln("Rocks!\n");
            exitprogram
        label(010101101)
            writeln("Hello ");
            goto(011001101)
    end
endprogram

Incidentally if you want to hire me to not write shit this bad, PM me as I've had enough of my current job ;)

Edit: make it more disgusting.
« Last Edit: August 21, 2017, 08:28:52 pm by bd139 »
 
The following users thanked this post: mnementh

Offline glarsson

  • Frequent Contributor
  • **
  • Posts: 814
  • Country: se
Re: Function return in C
« Reply #37 on: August 21, 2017, 08:22:23 pm »
2. It's written entirely in ANSI C
No. The variable _u invades the namespace of the implementations. Any symbol starting with underscore followed by a letter or number is reserved for use by the implementation (compiler, runtime libraries etc).
 

Offline bd139

  • Super Contributor
  • ***
  • Posts: 23018
  • Country: gb
Re: Function return in C
« Reply #38 on: August 21, 2017, 08:27:22 pm »
Fair point. For ref I compiled with following flags. No warnings:

Code: [Select]
gcc -ansi -Wall -pedantic pisstake.c -o pisstake

via

Code: [Select]
CFLAGS="-ansi -Wall -pedantic" make pisstake
 

Offline glarsson

  • Frequent Contributor
  • **
  • Posts: 814
  • Country: se
Re: Function return in C
« Reply #39 on: August 21, 2017, 08:35:40 pm »
Fair point. For ref I compiled with following flags. No warnings:
Never seen a compiler give warning for that. Probably because the compiler must be able to parse system include files without complaining about it.
Same when user code uses symbol names like "strange" and "strut" after including strings.h.
 

Offline bd139

  • Super Contributor
  • ***
  • Posts: 23018
  • Country: gb
Re: Function return in C
« Reply #40 on: August 21, 2017, 08:37:19 pm »
Yeah I suppose those are pulled in by the preprocessor anyway so there's no context so see whom it belonged to by the time the compiler does it's first pass.
 

Offline Howardlong

  • Super Contributor
  • ***
  • Posts: 5317
  • Country: gb
Re: Function return in C
« Reply #41 on: August 21, 2017, 10:08:54 pm »
Hmm, interesting, I've used single underscores to identify global variables in my own code since the late 80s. I've always been aware that the compiler uses double underscores. It came from a book I was reading on Windows API programming around 1989, and that, along with a slightly modified and extended Hungarian notation is what I've used in my own C code ever since, although I realise Hungarian notation fell out of popularity a couple or decades ago ;-)

Edit: looks like I get away with it as the rule for ANSI C apparently is that two leading underscores are reserved, as is one underscore followed by an upper case letter. In Hungarian notation, the first letter of a variable is always lower case.

I'd imagine the example _u therefore is also legal, it being a lower case "u".
« Last Edit: August 21, 2017, 10:24:33 pm by Howardlong »
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11622
  • Country: my
  • reassessing directives...
Re: Function return in C
« Reply #42 on: August 22, 2017, 12:05:51 am »
when is the last time you use "if"? thats a forward jump... when is the last time you use "while" and "for"? thats the backward jump. except the language has made them a little bit organized for you ;) 
No that is called a "conditional loop", if  you were serious I would advise you to pick up your books again  :)
if it happens that a language inventor in the book want to call it chicken then it will be called "conditional chicken". machine only can do jump and skip... can machine encapsulate? ;) btw if goto and return is so bad, they should have made it unavailable in their language syntax list... just like you cant alloc(), "new" or use pointer in ada/java/phyton/pascal...
Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 

Offline Kjelt

  • Super Contributor
  • ***
  • Posts: 6460
  • Country: nl
Re: Function return in C
« Reply #43 on: August 22, 2017, 07:04:44 am »
if it happens that a language inventor in the book want to call it chicken then it will be called "conditional chicken". machine only can do jump and skip... can machine encapsulate? ;) btw if goto and return is so bad, they should have made it unavailable in their language syntax list... just like you cant alloc(), "new" or use pointer in ada/java/phyton/pascal... 
Well if you look at the K&R bible they make explicit difference between Iteration statements (while,do,for) and Jump statements (goto,continue,break,return) where they explicitly mention they don't use goto in their book and only see a valid use case for a goto statement in an exception occurring inside a two or multiple loop statement to break out directly.
 

Offline glarsson

  • Frequent Contributor
  • **
  • Posts: 814
  • Country: se
Re: Function return in C
« Reply #44 on: August 22, 2017, 07:37:10 am »
... just like you cant alloc(), "new" or use pointer in ada/java/phyton/pascal...
Why do you think you can't use pointers in Ada? Look for access types and access attribute.
 

Offline Brumby

  • Supporter
  • ****
  • Posts: 12297
  • Country: au
Re: Function return in C
« Reply #45 on: August 22, 2017, 12:15:02 pm »
While I support the preference to avoid using the goto, I do not exclude it completely.  BUT - I have some very simple guidelines for its use.  The first and foremost is that it is always used to branch to a forward point down the code.  Never backward.  The second is that it is not used in normal program logic - only for exception situations.

A third point would be not to jump inside a block from outside.

Into or out of (ie past the local proximity).

That did cross my mind when writing that post - but it is so fundamentally wrong, I didn't think it necessary to specifically mention.
« Last Edit: August 22, 2017, 12:20:02 pm by Brumby »
 

Offline Brumby

  • Supporter
  • ****
  • Posts: 12297
  • Country: au
Re: Function return in C
« Reply #46 on: August 22, 2017, 12:32:27 pm »
when is the last time you use "if"? thats a forward jump... when is the last time you use "while" and "for"? thats the backward jump. except the language has made them a little bit organized for you ;)

Ridiculous argument.  If you really want to get silly - let's just cut to the machine code.  Every non sequential transfer of control is a jump.

The behind-the-scenes of the higher level language is not the issue.  What is being discussed is the human coding level.
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11622
  • Country: my
  • reassessing directives...
Re: Function return in C
« Reply #47 on: August 22, 2017, 06:00:58 pm »
What is being discussed is the human coding level.
wanna get safe? program in Ada ;D or any highest level programming you can find that doesnt provide goto and return. ;D well i'm not serious and i dont want this thread into language battle anyway... maybe this is my personal preferences i see all language will be translated to machine language anyway, so all these concepts in programming practises is a theoritical matters on the higher level made by the language architects, in the end, we human as the software dveloper needs to take care of it ourself, no grant, even if you program in Ada... a virus injecting your Ada compiled program, you'll have the blue screen of death, or some malicious act in behind, well...
Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 

Offline tggzzz

  • Super Contributor
  • ***
  • Posts: 19468
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Function return in C
« Reply #48 on: August 22, 2017, 06:55:20 pm »
i see all language will be translated to machine language anyway, so all these concepts in programming practises is a theoritical matters on the higher level made by the language architects

Why stop there at an externally visible ISA? Why not continue your proposition to the microcode architecture hidden inside many modern processors (or explicitly available in older ones like the HLH Orion)?

Why stop there? Why not continue to a register-transfer-level definition?

Why stop there? Why not continue to a transistor-level definition?

Answer: raising the abstraction level allows more complex systems to be designed and implemented.

So while on a theoretical level transistors can do everything that OOP/functional/logic/relational/FSM/etc language can do, on a practical level there is a very significant difference - and which type of higher-level abstraction can greatly simplify or hinder a system's implementation
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11622
  • Country: my
  • reassessing directives...
Re: Function return in C
« Reply #49 on: August 22, 2017, 11:38:39 pm »
Why stop there? Why not continue to a transistor-level definition?
because i and most hackers can access machine code easily through the App's binary. trying to hack at the hardware level, we need good bunch of heavy stuffs, only the enemy of the state has them, so seldom case is not interesting... plus i dont consider transistor's logic as "programming" at all, they just "tools" to serve our "programming logic", or "software science". plus a transistor cannot jump or skip another transistor by any physical or theoritical means. the idea of jump and skip starts at programming/software logic flow...
Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf