讨论printf和cout的参数调用顺序

来源:互联网 发布:30岁男士护肤 知乎 编辑:程序博客网 时间:2024/05/22 13:37

这里纠正在网络上看到的几个错误,以下给出正确的观点:

(1)printf和cout都是有缓冲机制的。(有人认为printf是没有缓冲区的)

(2)printf和cout函数对参数的调用顺序在c/c++中是未定义的。(有人认为它们读入的顺序是由右向左,输出顺序是由左到右,类似于栈)


基于以上错误的认识,看下列程序,有人会得到错误的输出的结果。

#include <stdio.h>#include <iostream>using namespace std;int main() {int value, value2;        //Aint a = 3;printf("printf a: %d  %d\n", a++, a++);cout << "after a: " << a << endl << endl;        //B        int d = 3;cout << "cout d: " << d++ << " " << d++ << endl;cout << "after d: "  << d << endl << endl;        //Cint c = 3;printf("printf c: %d  %d\n", c++, ++c);cout << "after c: " << c << endl << endl;        //D                int b = 3;cout << "cout b: " << b++ << " " << ++b << endl;cout << "after b: " << b << endl << endl;        //E 该部分代码是<span style="color:#3366FF;">《程序员面试宝典第四版32页》的题</span>int arr[] = {6,7,8,9,10};int *ptr = arr;*(ptr++) += 123;printf("%d, %d\n", *(ptr++), *(++ptr));        //cout << *(ptr++) << " " << *(++ptr) << endl; }
以上程序在Visual studio 2010中的运行结果如下图:

但是在g++下的运行结果如下图:

        因此可以看出,printf和cout对参数的调用顺序是根据编译器而定的,在C/C++标准中并没有规定这两者对参数的调用次序。上述输出的不同跟缓冲区毫无关系。

       但注意在代码中E部分的代码(该部分代码是《程序员面试宝典第四版32页》的题)中,printf在两个编译器下的执行结果是一样的。但是如果使用cout输出的话(如代码的最后一行注释),则在vs2010下的执行结果是"8 9",而在g++下的执行结果是”10 10“。


这部分内容搞得很混乱,求大神指教。

0 0