gpt4 book ai didi

c - 为什么 C 程序给出不同的结果?

转载 作者:太空狗 更新时间:2023-10-29 16:32:03 26 4
gpt4 key购买 nike

我参加的考试中有一道题。问题是:

以下代码的输出是什么:

#include<stdio.h>
#include<conio.h>

void main()
{
int a=5, b=6, c=7;
printf("%d%d%d");
}

我的回答:它会发出警告,因为 printf 没有提供所需的参数。
如果您运行它,您将获得垃圾值。

老师给了我零分。根据他的说法,答案是这些值将以相反的顺序打印,即输出将是“765”。

问题是他使用的是 Turbo C++ 编译器,而我通常使用 GCC。我可以提出一些意见和解释来取回我的分数吗?还是我的答案真的错了?

最佳答案

这是一个未定义的行为,所以任何事情都可能发生。

局部变量可能实际上被打印出来,因为在某些系统上Xprintf 函数系列可能会从堆栈中弹出它们的参数(stdarg.h 工具可用于实现这样的功能)。您的变量 a,b,c 可能恰好位于 va_arg 宏将从中提取参数的内存位置。这些是库实现/执行环境的详细信息,不是标准的一部分,因此它们可能因不同的目标平台而异。

这里是 c99 标准中描述 fprintf 函数的引述:

7.19.6.1 The fprintf function

2/ The fprintf function writes output to the stream pointed to by stream, under control of the string pointed to by format that specifies how subsequent arguments are converted for output. If there are insufficient arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored. The fprintf function returns when the end of the format string is encountered.

关于c - 为什么 C 程序给出不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13133979/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com