Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4208600
  • 博文数量: 176
  • 博客积分: 10059
  • 博客等级: 上将
  • 技术积分: 4681
  • 用 户 组: 普通用户
  • 注册时间: 2006-03-24 12:27
文章分类

全部博文(176)

文章存档

2012年(1)

2011年(4)

2010年(14)

2009年(71)

2008年(103)

分类: C/C++

2008-11-29 14:31:22

cout,printf输出问题

By zieckey (http://blog.chinaunix.net/u/16292/index.html)

话说这是08年11月份IBM招聘的笔试题,感觉蛮有意思的。
好了,废话少说见程序:

#include
using namespace std;

int fun(  )
{
    cout << "f" ;
    return 1;
}
int main()
{
    
    int i = 1;
    cout << i++ << i++ << i++ << endl;
    cout << "m" << fun() << fun() << fun() << endl;
    return 1;
}



输出:
321
fffm111

如果只针对题来说的话,实际是这样的
cout<<"m"<对于<<其实是从右往左处理的。于是碰到fun()必然先输出f,然后返回1,于是就变成了
cout<<"m"<继续往左走,直到 cout<<"m"<<1<<1<<1 ;的时候已经输出了fff ,之后就是按顺序输出了m111, 所以看到的结果就是 fffm111 




题目稍微更改下,看看输出就更好理解了:

#include
#include
using namespace std;

int fun( int i )
{
    cout <    return i;
}
int main()
{
   
    int i = 1;
    cout << i++ << i++ << i++ << endl;
    cout << "m" << fun(1) << fun(2) << fun(3) << endl;

    printf("m%d%d%d\n", fun(1),fun(2),fun(3));
    return 1;
}
输出:
321
3f2f1fm123
3f2f1fm123

说明:cout、printf等都是从右向左处理的,先计算,然后再一次性输出。
阅读(2768) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~