如果让c程序更短

写程序的一个规则就是, 在保证代码优美/可读性的情况下, 尽可能的短. 逻辑能用三行就绝不用五行.

 

1. 用for取代while

/* With while: */
a = 0;
b = 0;
while (a < 10) {
    a++;
    b++;
}    

/* With for: */
for (a = b = 0; a < 10; a++, b++);

2. 在if中写入逻辑:

/* 原代码: */
a = method1();
if (a == 0) {
    b = method2();
    if (b == 0)
        method3();
}

/* 改为: */
if ((a = method1()) == 0)
    if ((b = method2()) == 0)
        method3();

3. 去掉if嵌套, 因为很多时候需要满足一行80字的代码规则, 很多嵌套会使每行可写的字数变少.

int func1(Node *p) 
{
    if ( p != NULL) {
        // blabla
        if (func2() == 0) {
            // blabla
            func3();
       }
    }
}        

/* => */
int func1(Node *p) 
{
    if ( p == NULL) 
        return;
    // blabla
    if (func2() == 0) {
        // blabla
        func3();
    }
}

 

posted @ 2016-03-23 14:36  brayden  阅读(183)  评论(0编辑  收藏  举报