"while/else" (ugh) (was Re: [oclug] Ruby)

Matthew Wilcox willy at debian.org
Fri Jun 27 21:48:29 EDT 2003


On Fri, Jun 27, 2003 at 06:58:43PM -0400, Francis J. A. Pinteric wrote:
> `goto' constructs are anathema!  In C, a `goto' generally signifies
> badly designed code. Sometimes they are unavoidable, but for 99% of the
> cases, a goto is completely unnecessary.  Didn't you read all those
> papers in the late '70's about goto-less C code? :-)

here, let's take a real world example.  rewrite this without gotos and tell
me it's clearer:

static inline long do_sys_truncate(const char __user * path, loff_t length)
{
        struct nameidata nd;
        struct inode * inode;
        int error;

        error = -EINVAL;
        if (length < 0) /* sorry, but loff_t says... */
                goto out;

        error = user_path_walk(path, &nd);
        if (error)
                goto out;
        inode = nd.dentry->d_inode;

        /* For directories it's -EISDIR, for other non-regulars - -EINVAL */
        error = -EISDIR;
        if (S_ISDIR(inode->i_mode))
                goto dput_and_out;

        error = -EINVAL;
        if (!S_ISREG(inode->i_mode))
                goto dput_and_out;

        error = permission(inode,MAY_WRITE);
        if (error)
                goto dput_and_out;

        error = -EROFS;
        if (IS_RDONLY(inode))
                goto dput_and_out;

        error = -EPERM;
        if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
                goto dput_and_out;

        /*
         * Make sure that there are no leases.
         */
        error = break_lease(inode, FMODE_WRITE);
        if (error)
                goto dput_and_out;

        error = get_write_access(inode);
        if (error)
                goto dput_and_out;

        error = locks_verify_truncate(inode, NULL, length);
        if (!error) {
                DQUOT_INIT(inode);
                error = do_truncate(nd.dentry, length);
        }
        put_write_access(inode);

dput_and_out:
        path_release(&nd);
out:
        return error;
}

i'm not just being a smartarse here -- i used to believe that Goto Was
Harmful until I started converting code like this and realised I was
doing more harm than good.

-- 
"It's not Hollywood.  War is real, war is primarily not about defeat or
victory, it is about death.  I've seen thousands and thousands of dead bodies.
Do you think I want to have an academic debate on this subject?" -- Robert Fisk



More information about the OCLUG mailing list