• cout的参数输出顺序问题


    今天去参加人人网笔试,遇到这样一个题目:

    问下面代码的输出是什么?

    1. #include <iostream>  
    2. using namespace std;  
    3.   
    4. int g = 0;  
    5. template<typename T>  
    6. int foo()  
    7. {  
    8.     int value = ++g;  
    9.     return value;  
    10. }  
    11.   
    12. int main()  
    13. {  
    14.     cout << foo<int>() << foo<char>() << foo<float>() << foo<double>() << endl;  
    15.   
    16.     return 0;  
    17. }  

    乍一看,觉得这个题目没那么简单,但是又想不出到底输出什么,就只好填了1234,其实这个结果是错的。

    回来在vc上运行了下,果然不是1234,而是4321。百思不得其解,后来在网上搜了下,发现cout的输出顺序有如下规律:

    计算顺序:自右至左

    输出顺序:自左至右

    也就是说cout在计算的时候是先计算foo<double>()的值为1,再计算foo<float>()的值为2,。。。所以输出是4321。

    后来用C的printf测了一下,也是输出4321。

    为什么cout和printf会以这样的方式运行的?

       很多的编译器在函数调用的时候,会在内存中分配一个函数调用栈,函数的参数总是从右往左的顺序计算并进栈。

  • 相关阅读:
    leetcode算法题基础(五)双指针(一)27 题 移除元素
    kata-shim: Setctty set but Ctty not valid in child: unknown.
    kata-runtime mount
    UVa1636 Headshot
    HDU1150 Machine Schedule
    POJ 1273 Drainage Ditches
    SPOJ GSS1 Can you answer these queries I
    POJ 1840 Eqs
    POJ2001 Shortest Prefixes
    HDU 2795 Billboard
  • 原文地址:https://www.cnblogs.com/cobbliu/p/2388561.html
Copyright © 2020-2023  润新知