我们先来看一个简单的程序:
- #include <iostream>
- using namespace std;
-
- #define fun() \
- cout << "a" << endl; \
- cout << "b" << endl;
-
- int main()
- {
- int i = 0;
- for(i = 0; i < 2; i++)
- {
- fun();
- }
-
- return 0;
- }
结果为:
a
b
a
b
我们再看看程序:
- #include <iostream>
- using namespace std;
-
- #define fun() \
- cout << "a" << endl; \
- cout << "b" << endl;
-
- int main()
- {
- int i = 0;
- for(i = 0; i < 2; i++)
- fun();
-
- return 0;
- }
结果为:
a
a
b
上述两个程序的结果居然不一样,是for用错了吗?不是的。在第二个程序中,for虽然用得不好,但没有什么语法和逻辑错误,至于结果为什么不一样,那是因为在用宏的时候,没有使用大括号,所以应该加上大括号,如下:
- #include <iostream>
- using namespace std;
-
- #define fun() \
- {\
- cout << "a" << endl; \
- cout << "b" << endl; \
- }
-
- int main()
- {
- int i = 0;
- for(i = 0; i < 2; i++)
- fun();
-
- return 0;
- }
结果为:
a
b
a
b
虽然上面程序中for的用法是对的,但并不好,所以尽量改为:
- #include <iostream>
- using namespace std;
-
- #define fun() \
- {\
- cout << "a" << endl; \
- cout << "b" << endl; \
- }
-
- int main()
- {
- int i = 0;
- for(i = 0; i < 2; i++)
- {
- fun();
- }
-
- return 0;
- }
结果为:
a
b
a
b
这样就万事大吉了吗?非也,非也!请看程序:
- #include <iostream>
- using namespace std;
-
- #define fun() \
- {\
- cout << "a" << endl; \
- cout << "b" << endl; \
- }
-
- int main()
- {
- if(1 > 0)
- fun();
- else
- fun();
-
- return 0;
- }
这个程序的结果是什么呢?结果是:编译出错!为什么呢?下面,我们给出上述程序的等价形式:
- #include <iostream>
- using namespace std;
-
- int main()
- {
- if(1 > 0)
- {
- cout << "a" << endl;
- cout << "b" << endl;
- }; // 注意:这里有个分号,所以if部分已经结束了
- else // 此处else没有匹配的if, 所以编译出错
- {
- cout << "a" << endl;
- cout << "b" << endl;
- }
-
- return 0;
- }
现在明白了吧?那么,应该怎么改呢? 当然,如果你用下面的方式,那也是可以解决问题的:
- #include <iostream>
- using namespace std;
-
- #define fun() \
- {\
- cout << "a" << endl; \
- cout << "b" << endl; \
- }
-
- int main()
- {
- if(1 > 0)
- {
- fun();
- }
- else
- {
- fun();
- }
-
- return 0;
- }
但是,你怎么可能保证项目中某些“程序猿”在用if else时能时时带上大括号呢?既然保证不了,那就用do while(0)吧,如下:
- #include <iostream>
- using namespace std;
-
- #define fun() do \
- {\
- cout << "a" << endl; \
- cout << "b" << endl; \
- } while(0) // 注意,此处不要加分号
-
- int main()
- {
- if(1 > 0)
- fun();
- else
- fun();
-
- int i = 0;
- for(i = 0; i < 2; i++)
- fun();
-
- cout << endl;
-
- // 当然,更好的方式是:
- if(1 > 0)
- {
- fun();
- }
- else
- {
- fun();
- }
-
- for(i = 0; i < 2; i++)
- {
- fun();
- }
-
- return 0;
- }
OK, 至此才万事大吉。下次再看在项目中看到do while(0)的时候,不要再大吃一惊。