zoukankan      html  css  js  c++  java
  • c++cout执行顺序之一个不容易注意到的一点

    二话不说,先看一个例子

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        int a[10]={1,12,34,56,78,89,90,8,9,0};
        int *p=a;
        int *p2=a;
        cout<<++*p<<endl;
        cout<<*++p<<endl;//谁靠的近先执行谁
        cout<<endl;
        cout<<++*p2<<"    "<<*p2<<"    "<<*++p2<<endl;
        char *st[]={"asd","qwe","zxc"};
        char**q=st;
        cout<<*++q<<endl;
        cout<<*q<<endl;
        return 0;
    }

    运行结果

    2
    12

    13    12    12
    qwe
    qwe

    是不是很interesting,本来是探究++与解指针运算符*的优先级的问题,引发了一个有关cout执行顺序的问题。
    其实这两的优先级一样都为2

    为什么p2的输出就成了这个样子,而并不是我们所认为的2    2    12.

    种种事实表明,cout的运行时候执行顺序是从右往左,是符合栈的执行模型的。再来个例子

    #include <iostream>
    
    using namespace std;
    
    int  f1()
    {
        cout<<"f1"<<endl;
        return 1;
    }
    int  f2()
    {
        cout<<"f2"<<endl;
        return 2;
    }
    int  f3()
    {
        cout<<"f3"<<endl;
        return 3;
    }
    
    int main()
    {
        cout <<"first--"<<f1()<<"   second--"<<f2()<<"   third--"<<f3()<< endl;
        return 0;
    }

     可以看到运行结果为

    f3
    f2
    f1
    first--1   second--2   third--3

    Process returned 0 (0x0)   execution time : -0.000 s
    Press any key to continue.

    这明显证明cout在执行的时候为从右向左先执行,然后在输出的时候为按照原来的顺序在从左像右的输出

  • 相关阅读:
    eclipse经常卡死、反应慢、内存溢出的解决方案
    PAC4J 初探
    suse11离线安装nginx
    linux修改乱码的文件名
    CentOS修改服务器系统时间
    Unable to open nested entry '********.jar' 问题解决
    openssl req(生成证书请求和自建CA)
    CRT证书转JKS证书
    如何创建一个自签名的SSL证书(X509)
    Redis分布式锁的深度剖析
  • 原文地址:https://www.cnblogs.com/freedom314/p/5864365.html
Copyright © 2011-2022 走看看