Chinaunix

标题: 求解一个奇怪的输出 [打印本页]

作者: Coolriver    时间: 2010-01-01 12:21
标题: 求解一个奇怪的输出
这个题有点考试的题了,没搞明白特来请教一下.
程序我从中扣出来一点,也是测试程序:

  1. #include <stdio.h>
  2. main()
  3. {
  4.     int i=8;
  5.     printf("i=%d\n",i);
  6.     printf("++i=%d\n--i=%d\n",++i,--i);
  7. }
复制代码


运行解果:

  1. i=8
  2. ++i=8
  3. --i=8
复制代码


gcc -v
Using built-in specs.
Target: i386-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-libgcj-multifile --enable-languages=c,c++,objc,obj-c++,java,fortran,ada --enable-java-awt=gtk --disable-dssi --enable-plugin --with-java-home=/usr/lib/jvm/java-1.4.2-gcj-1.4.2.0/jre --with-cpu=generic --host=i386-redhat-linux
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)

请高人指点一下,是不是这个版本有Bug了.

[ 本帖最后由 Coolriver 于 2010-1-1 12:23 编辑 ]
作者: drangon    时间: 2010-01-01 12:24
永远不要在一个表达式中多次修改同一个变量,这样的行为是未定义的,标准允许编译器按任何的结果实现
作者: churchmice    时间: 2010-01-01 12:45
版主这个属于挖坑么?
如ls所说,这个是undefined的行为,去看看c标准就知道了
作者: Coolriver    时间: 2010-01-01 13:35
哈,今天搞出飞机了.一个朋友问我C的运算上的东西.我给说是从左向左的,写了一个程序测试巨然出现上面的垃圾事情.
又加了一点:
#include <stdio.h>

main()
{
    int i=8;
    printf("++i=%d\n--i=%d\ni++=%d\ni--=%d\n-i++=%d\n-i--=%d\n",
            ++i,--i,i++,i--,-i++,-i--);
}

输出还是:
++i=8
--i=8
i++=7
i--=8
-i++=-7
-i--=-8

问题还是出在--i上不正确.
作者: churchmice    时间: 2010-01-01 14:52
标题: 回复 #4 Coolriver 的帖子
ISO/IEC 9899:1999 (E)第72页
6.5.2.2 Function calls
10 The order of evaluation of the function designator, the actual arguments, and
subexpressions within the actual arguments is unspecified, but there is a sequence point
before the actual call.


找了个sun的机器帮你试了下
bmw(2)cc test.c -Wall -o test
test.c:4: warning: return-type defaults to `int'
test.c: In function `main':
test.c:8: warning: control reaches end of non-void function
bmw(3)./test
++i=9
--i=8
i++=8
i--=9
-i++=-8
-i--=-9

这种问题就别纠结了

[ 本帖最后由 churchmice 于 2010-1-1 14:54 编辑 ]
作者: pmerofc    时间: 2010-01-01 19:52
提示: 作者被禁止或删除 内容自动屏蔽
作者: zhaohongjian000    时间: 2010-01-02 15:51
确实是unspecified哎,不过不管怎么说,都应该避免的。
作者: pmerofc    时间: 2010-01-02 17:07
提示: 作者被禁止或删除 内容自动屏蔽
作者: Coolriver    时间: 2010-01-02 22:54
谢谢,以上各位高人指点.以前对于这个细节没多注意.唉,不经常写程序,学习不到位.以后多努力.
作者: pmerofc    时间: 2010-01-03 09:06
提示: 作者被禁止或删除 内容自动屏蔽




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2