是scanf(“%4s%4s”,b,b);定义明确? [英] Is scanf("%4s%4s", b, b); well-defined?

查看:117
本文介绍了是scanf(“%4s%4s”,b,b);定义明确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include< stdio.h> 

int main(void)
{
char b [5];
scanf(%4s%4s,b,b);
//我的输入: qwer< Enter> sgsh< Enter>
printf(%s,b);
//输出:sgsh
}

C99:



在这种情况下,我要修改一个对象的上一个和下一个序列点,其存储值
最多只能修改一次。 b 两次的值。 未定义的行为,不是吗?

解决方案

来自 scanf 参考


有每个转换说明符作用后的序列点;这样可以将多个字段存储在同一个接收器变量中。


因此,您正在执行的操作已定义并且应该可以正常工作。 / p>

#include <stdio.h>

int main(void) 
{
    char b[5];
    scanf("%4s%4s", b, b);
    //My input: "qwer<Enter>sgsh<Enter>"
    printf("%s", b);
    //Output: sgsh
}

C99: Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.

In this case, I am modifying the value of b twice. Isn't it undefined behavior?

解决方案

From this scanf reference:

There is a sequence point after the action of each conversion specifier; this permits storing multiple fields in the same "sink" variable.

So what you're doing is defined and should work well.

这篇关于是scanf(“%4s%4s”,b,b);定义明确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆