对于短整型scanf函数的奇怪行为 [英] strange behavior of scanf for short int

查看:1038
本文介绍了对于短整型scanf函数的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在code是如下:

#include <stdio.h>
main()
{
    int m=123;
    int n = 1234;
    short int a;
    a=~0;
    if((a>>5)!=a){
        printf("Logical Shift\n");
        m=0;
    }
    else{
        printf("Arithmetic Shift\n");
        m=1;
    }
    scanf("%d",&a);
    printf("%d\n", m);
}

后scanf函数(%d个,&安培; A); m的值变 0

我知道它可能由scanf的原因引起:一个的类型是短且输入的类型是int。但是,这又如何影响m的值?

I know it may be caused by the scanf: a's type is short and the input's type is int. But How can this affect the value of m ?

非常感谢!

推荐答案

最可能的原因为 M 0 在你的片段是因为您分配 M 来在你的if语句,但由于code包含的未定义行为没有人可以说是肯定的。

The most likely reason for m being 0 in your snippet is because you assign m to have this value in the body of your if-statement, but since the code contains undefined behavior no one can say that for sure.

假设的sizeof(短)= 2 的sizeof(int)的== 4

当输入您的主要功能在其上驻留的变量通常会看起来像在堆栈下面:

When entering your main function the stack on which the variables reside would normally look something like the below:

  _
 |short int (a)   : scanf will try to read an int (4 bytes).
 |_ 2 bytes       : This part of memory will most
 |int       (n)   : likely be overwritten
 |                :..
 |
 |_ 4 bytes
 |int       (m)
 |
 |
 |_ 4 bytes

当你读了%d个(即一个 INT )到变量一个,不应该影响变量 M ,虽然 N 将极有可能的地方它覆盖。

When you read a %d (ie. an int) into the variable a that shouldn't affect variable m, though n will most likely have parts of it overwritten.

虽然这一切都一个猜谜游戏,因为你正在调用我们通常所说的未定义行为的使用scanf函数语句时。

Though it's all a guessing game since you are invoking what we normally refer to as "undefined behavior" when using your scanf statement.

一切的标准并不能保证是UB,其结果可能是什么。也许你会写数据到另一个段这是一个不同变量的一部分,或者你可能会使宇宙破灭。

Everything the standard doesn't guarantee is UB, and the result could be anything. Maybe you will write data to another segment that is part of a different variable, or maybe you might make the universe implode.

没有人可以保证,我们会活着看到另一天,当UB为present。

Nobody can guarantee that we will live to see another day when UB is present.

使用%HD ,并确保它传递一个短* ..我们已经受够了UB一晚!

Use %hd, and be sure to pass it a short*.. we've had enough of UB for one night!

这篇关于对于短整型scanf函数的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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