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在执行的时候为从右向左先执行,然后在输出的时候为按照原来的顺序在从左像右的输出

  • 相关阅读:
    Python模块、包、异常、文件(案例)
    jQuery DataTable 删除数据后重新加载
    Python|面向对象
    python开发的学生管理系统
    使用JDK开发WebServrice案例
    Python入门(案例)
    Spring总结以及在面试中的一些问题
    Web Services简单介绍
    Canvas实现文字粒子化,并且绕轴旋转(完善)
    HTML5 Canvas画数字时钟
  • 原文地址:https://www.cnblogs.com/freedom314/p/5864365.html
Copyright © 2011-2022 走看看