zoukankan      html  css  js  c++  java
  • printf("%d, %d ", i++, ++i)的输出结果是确定的吗???

    1. 问题描述

    以下代码的输出结果是什么?

    题目1:

    int i=10;
    printf("%d, %d
    ", i++, ++i);

    题目2:

    int i = 3;
    printf("%d, %d, %d, %d, %d
    ", i++, ++i, i, i++, i);

    2. 解题思路【错误】

      printf参数是从右至左入栈的,故:

    • 题目1的输出为:11,12
    • 题目2的输出为:

    3. 反思

    • 注意:该类题目编译器不一样,结果就会不一样,即这种行为依赖编译器!!!不必纠结。
    • 原因分析:
      • C/C++语言没有规定具体压栈顺序,没有标准化时C语言支持没有固定参数的函数,所以为了实现这个当时多数编译器都采用从右往左压栈,但是标准化的要求至少有一个固定参数,这个限制就没有必要了。不过从右到左几乎已经成为了C编译器惯用的顺序。C++的_stdcall方式也是采用从右到左,不同的只是不需要调用者自己手动清栈。
      • 另外求值顺序和压栈顺序是两回事,C语言里几乎没有对求值顺序做规定,编译器完全可以先求出值再决定如何压栈。
      • 简单说,这种问题与编译器实现语言的规定有关。不同编译器下生成的代码可能不同,出现的结果就不同。对于这种可能造成错误的代码,不用纠结。

    What's the value of i++ + i++?
    It's undefined. Basically, in C and C++, if you read a variable twice in an expression where you also write it, the result is undefined. Don't do that. Another example is:

    v[i] = i++;

    Related example: 

    f(v[i],i++);

    Here, the result is undefined because the order of evaluation of function arguments are undefined. 

    Having the order of evaluation undefined is claimed to yield better performing code. Compilers could warn about such examples, which are typically subtle bugs (or potential subtle bugs). I'm disappointed that after decades, most compilers still don't warn, leaving that job to specialized, separate, and underused tools.

  • 相关阅读:
    ASP.NET中使用javascript
    遍历DataList控件
    史上最强劲之android模拟器命令详解
    Android开发环境配置简介
    Android模拟器adb命令介绍
    听一名普通android应用开发人员谈:怎样成为一名Android开发者
    android模拟器安装及优化(集锦)
    Ubuntu 快捷键集锦
    smplayer 中文字幕乱码,进度条及拖放MKV
    如何在Windows下搭建Android开发环境
  • 原文地址:https://www.cnblogs.com/whl2012/p/5731385.html
Copyright © 2011-2022 走看看