为什么这个 printf 语句没有产生书中示例中所示的输出?
int j=5,k=9;
printf("%d...%d");
这个问题在一本书上。 给出的输出:5 9 但是当我尝试这个时,我得到:垃圾值,请向我解释一下。 书中的解释说 printf 取程序前两个赋值的值
int j=5,k=9;
printf("%d...%d");
This question was in a book.
output given : 5 9
But when i try this i got : garbage values, please explain this to me.
The explanation in the book says that printf takes values of first two assignments of the program
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你的书作者依赖的是愚蠢的行为。 (我不知道它是
未定义
还是实现定义
还是只是简单的愚蠢
。)它们依赖于你的堆栈分配
j
和k
变量在调用printf(3)
时神奇地存在。因为printf(3)
将使用其格式字符串来确定要读取多少个对象的类型,因此会神奇地将位于堆栈上的j
和k
变量解释为printf(的参数 3)
,就好像它们是故意传递给它的。这过于依赖“这一切如何在幕后运作”的魔力。除非这个代码块被“这段代码可能会告诉你......”和“永远不要做这么愚蠢的事情......”包围,否则这本书可能不值得进一步阅读。
Your book authors are relying on stupid behavior. (I don't know if it is
undefined
orimplementation defined
orjust plain stupid
.)They are relying on your stack-allocated
j
andk
variables magically being there whenprintf(3)
is called. Becauseprintf(3)
will use its format string to determine what types of how many objects to read, it would magically interpret thej
andk
variables, located on the stack, as arguments toprintf(3)
, as if they had been passed to it intentionally.This is relying too much on the magic of "how it all works behind the scenes". Unless this code block is surrounded with "This code might show you ..." and "Never do something this stupid..." then the book is probably not worth reading any further.
首先,如果你写
你会得到 5 9。
现在,printf 是一个可以获取可变数量参数的函数,它解析始终是第一个参数的字符串,并决定在哪里放置一个给定参数的值。这意味着编译器不会强制执行给函数的参数,这就是为什么您不会收到任何错误。
如果在函数调用中将参数压入堆栈(大多数情况下都是这种情况),则
printf
将看到%d
并将下一个 int 放入堆栈中,如下所示数字(等等),由于除了基本字符串之外您没有分配参数,因此堆栈上的数据与函数调用无关(它是相关的,但不是您想要的:))First, if you write
You will get 5 9.
Now,
printf
is a function that can get a variable number of arguments, it parses the String, which is always the first argument and decide where to put a value from the given arguments. This means that there is no enforcement by the compiler regarding the arguments given to the function and that's why you don't get any error.If the arguments are pushed to the stack in function call (which is the case most of the time) than
printf
will see%d
and put the next int on the stack as the number (and so on), since you didn't assign arguments except of the basic string, the data on the stack is not related to the function call (it is related, but it's not what you want :) )拿起其他书, printf("%d...%d");没有任何意义。您必须提供两个整数参数来替换格式字符串中的 %d 。
Pick up some other book , printf("%d...%d"); doesnt make any sense . You have to supply the two integer arguments to replace the %d in format string .
尝试:
Try: