So I've been hearing about the Single Entry/Single Exit (SESE) rule, and all I can find out about it is that it's good to have a single entry and a single exit (return) in your functions. Why is this?
So I've been hearing about the Single Entry/Single Exit (SESE) rule, and all I can find out about it is that it's good to have a single entry and a single exit (return) in your functions. Why is this?
Makes the code easier to read. You won't be jumping out of the code mid-function. It's not always easier to code, but it's easier to follow.
As you can see the switch statement has several cases where it exits the function. One particular case though waits to exit till the end of the function. Of course this is a stupid example but in a large function it's nice to know that there is a single exit at the end of it.Code:int Foo(int option) { switch (option) { case 1: /* Do stuff */ return 0; case 2: /* Do stuff */ break; case 3: DoSomething(); return 0; } return 0; }
Ah, I see, thanks for the response. I agree that it makes it more readable.
So is it safe to assume that there is no technical reason behind it?
No technical reason.
But a worse case is when you have a complex function that takes locks:
I found some code similar to this where I was working several years back - of course, the malloc returning NULL is a rare error condition, so the return was not executed particularly often - or at all - but if it happened, it would have locked the rest of the application completely.Code:int func() { ... lock(something); ... if (something) { if ((p = malloc(somesize))== NULL) return -1; } .... .... unlock(something); return 0; }
This is one of the cases where a goto is actually the RIGHT solution.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
Ok, I see, nice to see what you can use a goto for.
Thanks guys!!
ahhh now i see the real use of goto. If we dint had goto in that case defiantly we should have exited from the main. But this give more flexible by skipping some code of they though error occurred.
ssharish