do{}while(0) write single input single output function | C language

do{}while()This syntax is rarely used in C programming, until one day I read Mr. Li Xianjing's "System Programmer Growth Plan" and found that it still has this method of use.

We can use do{}while(0)to write single-in single-out functions .

In some functions, we hope to do some paired operations at the entry and exit of the function, such as memory application and release, file opening and closing, locking and unlocking, etc. In such a function, it can be designed as single input and single output. The advantage is that it is not easy to make mistakes in later maintenance.

Suppose we have a function in which there is competition for operations, then we add a lock mechanism to it, the code may be like this:

int data_process(const char* data)
{
    lock(mutex);

    // 异常判断1
    if(!condition1) {
        unlock(mutex);
        return -1;
    }

    // 异常判断2
    if(!condition2) {
        unlock(mutex);
        return -1;
    }

    data_convert(data);
    ...

    unlock(mutex);
    return 0;
}

The above function is not written with single input and single output, that is, there are many exits, so each exit must be remembered to be unlocked. If you change to the single-in-single-out writing method, the above situation will become easier, just remember to unlock at the last exit.

int data_process(const char* data)
{
    int ret = -1;
    lock(mutex);

    // do{}while(0) 函数体内不允许使用return
    do {
        // 异常判断1
        if(!condition1) {
            ret = -1;
            break;
        }

        // 异常判断2
        if(!condition2) {
            ret = -1;
            break;
        }

        data_convert(data);
        ...
        ret = 0;

    } while(0);

    unlock(mutex);
    return ret;
}

The improved code just needs to remember not do{}while(0)to use it in the code block , while the original code needs to check returnevery place for unlocking. returnPersonally, I think the do{}while(0)method is easier to remember, and when the members of the team are do{}while(0)familiar with the usage, once they see this structure appear, they can realize that this function has an organ like a conditioned reflex, and it returnneeds to be used with caution.

More

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325505988&siteId=291194637