并且计算了几种可能的结果30、24(错误的)。
没想到在GCC上运行结果竟然是25.
搞不懂为啥会算成这样的?是不是GCC的运算顺序和TC不同。该怎么算才能算出GCC的这种结果?(就用笔算,简单的计算一下)
代码: 全选
#include "stdio.h"
main()
{
int i=3,j=0;/*The real conclusion is 18. But why it shows 25?*/
j=i++*++i+i--*--i;
printf("j=%d",j);
}
代码: 全选
#include "stdio.h"
main()
{
int i=3,j=0;/*The real conclusion is 18. But why it shows 25?*/
j=i++*++i+i--*--i;
printf("j=%d",j);
}
代码: 全选
$ cat a.c
#include "stdio.h"
int main()
{
int i=3,j=0;/*The real conclusion is 18. But why it shows 25?*/
j=i++*++i+i--*--i;
printf("j=%d\n",j);
return 0;
}
$ splint a.c
Splint 3.1.1 --- 03 Nov 2006
a.c: (in function main)
a.c:5:15: Expression has undefined behavior (left operand uses i, modified by
right operand): i++ * ++i
Code has unspecified behavior. Order of evaluation of function parameters or
subexpressions is not defined, so if a value is used and modified in
different places not separated by a sequence point constraining evaluation
order, then the result of the expression is unspecified. (Use -evalorder to
inhibit warning)
a.c:5:15: Expression has undefined behavior (left operand modifies i, used by
right operand): i++ * ++i
a.c:5:23: Expression has undefined behavior (left operand uses i, modified by
right operand): i-- * --i
a.c:5:23: Expression has undefined behavior (left operand modifies i, used by
right operand): i-- * --i
a.c:5:20: Expression has undefined behavior (left operand uses i, modified by
right operand): i++ * ++i + i-- * --i
a.c:5:20: Expression has undefined behavior (left operand modifies i, used by
right operand): i++ * ++i + i-- * --i
Finished checking --- 6 code warnings
$ gcc -Wall a.c
a.c: 在函数‘main’中:
a.c:5: 警告: ‘i’上的运算结果可能是未定义的
a.c:5: 警告: ‘i’上的运算结果可能是未定义的
a.c:5: 警告: ‘i’上的运算结果可能是未定义的
$ ./a.out
j=25
$ gcc -Wall -O a.c
a.c: 在函数‘main’中:
a.c:5: 警告: ‘i’上的运算结果可能是未定义的
a.c:5: 警告: ‘i’上的运算结果可能是未定义的
a.c:5: 警告: ‘i’上的运算结果可能是未定义的
$ ./a.out
j=18
我那个有运行错误吗? ..hyxuzhimin 写了:我这里可以运行,没有错误。
代码: 全选
.file "test.c"
.section .rodata
.LC0:
.string "j=%d"
.text
.globl main
.type main, @function
main:
leal 4(%esp), %ecx
andl $-16, %esp
pushl -4(%ecx)
pushl %ebp
movl %esp, %ebp
pushl %ecx
subl $36, %esp
movl $3, -12(%ebp)
movl $0, -8(%ebp)
addl $1, -12(%ebp)
movl -12(%ebp), %eax
movl %eax, %edx
imull -12(%ebp), %edx
subl $1, -12(%ebp)
movl -12(%ebp), %eax
imull -12(%ebp), %eax
leal (%edx,%eax), %eax
movl %eax, -8(%ebp)
addl $1, -12(%ebp)
subl $1, -12(%ebp)
movl -8(%ebp), %eax
movl %eax, 4(%esp)
movl $.LC0, (%esp)
call printf
movl $0, %eax
addl $36, %esp
popl %ecx
popl %ebp
leal -4(%ecx), %esp
ret
.size main, .-main
.ident "GCC: (GNU) 4.2.4 (Debian 4.2.4-1)"
.section .note.GNU-stack,"",@progbits