Re: Goto statements in the Kernel

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Bernd Petrovitsch wrote:

On Sun, 2005-08-07 at 15:57 +0200, Thomas Petazzoni wrote:
Hi,

Bob Smith a écrit :

Why is that ? I googled up reasons like minimizing return points,
but is that it ?
Most of the time, 'goto' is used to minimize code duplication in error
handling.

Without 'goto':

int myfunc (void)
{
  ret = dosomething1();
  if (ret < 0)
    return ret;

  ret = dosomething2();
  if (ret < 0)
  {
    undosomething1();
    return ret;
  }

  ret = dosomething3();
  if (ret < 0)
  {
    undosomething2();
    undosomething1();
    return ret;
  }

  ret = dosomething4();
  if (ret < 0)
  {
    undosomething3();
    undosomething2();
    undosomething1();
    return ret;
  }
 return 0;
}

With 'goto':

int myfunc(void)
{
  ret = dosomething1()
  if (ret < 0)
    goto ret_dosomething1;

  ret = dosomething2()
  if (ret < 0)
    goto ret_dosomething2;

  ret = dosomething3()
  if (ret < 0)
    goto ret_dosomething3;

  ret = dosomething4()
  if (ret < 0)
    goto ret_dosomething4;

ret_dosomething4:
 undosomething3();
ret_dosomething3:
 undosomething2();
ret_dosomething2:
 undosomething1();
ret_dosomething1:
 return ret;
}

With 'if':
int myfunc(void)
{
  ret = dosomething1()
  if (ret >= 0) {
     ret = dosomething2()
     if (ret >= 0) {
        ret = dosomething3()
        if (ret >= 0) {
           ret = dosomething4()
           if (ret >= 0) {
              ...
           }
        }
        undosomething3();
     }
     undosomething2();
  }
  undosomething1();
 return ret;
}

Now remember that the kernel has 8 spaces indentation, not 3 as above.
Not that better, especially if your label names are quite descriptive.

	Bernd
Hi Bernd,
IMHO, there is a small problem with the code..
what if ret is > 0? Then the code within the if is executed, only to be undone after the execution of the if.

for example...

ret = dosomething1()
if (ret > 0) {
   /*do stuff */
   .......
}
undosomething1()
return ret;

if ret > 0, it will "do stuff" and then undo something1. That IIUC, is not the desired effect.
Am i right, or is this me misinterpreting the code?
Thanks
Rahul


--
Kernelnewbies: Help each other learn about the Linux kernel.
Archive:       http://mail.nl.linux.org/kernelnewbies/
FAQ:           http://kernelnewbies.org/faq/



[Index of Archives]     [Newbies FAQ]     [Linux Kernel Mentors]     [Linux Kernel Development]     [IETF Annouce]     [Git]     [Networking]     [Security]     [Bugtraq]     [Yosemite]     [MIPS Linux]     [ARM Linux]     [Linux RAID]     [Linux SCSI]     [Linux ACPI]
  Powered by Linux