C 语言,碰到个很让人疑惑的问题

2018-12-04 17:15:04 +08:00
 xjr1022

//声明函数
void test(int a, int b);

int main() {
	int a = 2;
	test(a, a++);
	return 0;
}

void test(int x, int y) {

	printf("x=%d,y=%d", x, y);

}

//运行结果 
x=3,y=2

想请教一下这个是为什么呢,明明给形参 y 传递的是自增的量,怎么就 x 变成 3,而 y 还是 2,

3404 次点击
所在节点    C
45 条回复
shylockhg
2018-12-04 17:19:14 +08:00
从右边传参数
xjr1022
2018-12-04 17:23:34 +08:00
@shylockhg 麻烦您能说的详细点吗,谢谢了
misaka19000
2018-12-04 17:23:52 +08:00
在我电脑上面的运行结果
x=2,y=2
make
2018-12-04 17:24:03 +08:00
a++的返回值是自增之前的值,++a 的返回值才是自增之后的值
函数调用最后的参数先压栈
wutiantong
2018-12-04 17:26:08 +08:00
在 C++里这属于典型的 ub 了,因为函数传参时 eval 顺序是未定义的。
单就这个例子来说,先算了(a++) 后算了(a),结果没毛病。
shylockhg
2018-12-04 17:26:29 +08:00
这个很尴尬。。。
clang 3,2
gcc 2,2
shylockhg
2018-12-04 17:28:12 +08:00
@shylockhg 不过 clang 报了警告,估计对这个做了 trick 处理
kljsandjb
2018-12-04 17:29:06 +08:00
视 calling convention 而定吧
shylockhg
2018-12-04 17:29:09 +08:00
@shylockhg 反了
clang 2,2
gcc 3,2
lovefantasy
2018-12-04 17:30:43 +08:00
等一个解释
KingHL
2018-12-04 17:31:26 +08:00
谁这么写代码,直接打死
xjr1022
2018-12-04 17:33:07 +08:00
@KingHL 是一道蛋疼的试题
WuwuGin
2018-12-04 17:35:15 +08:00
The language clearly says that certain things lead to undefined behavior. There is no problem, there is no "should" involved. If the undefined behavior changes when one of the involved variables is declared volatile, that doesn't prove or change anything. It is undefined; you cannot reason about the behavior.

https://stackoverflow.com/a/949443

https://en.wikipedia.org/wiki/Sequence_point

总结:在实际编程中,不应该出现这种二义性的行为。探讨此类问题没有实际意义。
des
2018-12-04 17:35:27 +08:00
不要这么写,这都什么鬼。顺手给你加一点好了
test(++a, a++)
KingHL
2018-12-04 17:38:28 +08:00
参数入栈顺序从右向左,具体实现还要看不同的编译器行为,实际工程应用中,应该禁止这种不确定性的代码。如果是试题的话,估计是在考察你参数入栈顺序这个知识点。
xi2008wang
2018-12-04 17:38:48 +08:00
xjr1022
2018-12-04 17:39:25 +08:00
@WuwuGin 是的,真实开发相信没人这么写,这是一道考研真题。。。。
xjr1022
2018-12-04 17:42:25 +08:00
@des 这就要问出题老师怎么想的了,哈哈
xjr1022
2018-12-04 17:43:17 +08:00
@misaka19000 试试 gcc 下编译,有惊喜
WordTian
2018-12-04 17:43:27 +08:00
看编译器用的什么调用约定。。。
就是参数是从左往右还是从右往左

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/514267

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX