Re: Goto statements in the Kernel

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

 



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
-- 
Firmix Software GmbH                   http://www.firmix.at/
mobil: +43 664 4416156                 fax: +43 1 7890849-55
          Embedded Linux Development and Services




--
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