【问题标题】:Why the below code is giving different output when variable type is different?为什么当变量类型不同时下面的代码给出不同的输出?
【发布时间】:2016-09-21 16:30:30
【问题描述】:
//o/p when i/p is 16 and 2 is 4 and if  variable is int then o/p will be 20;   

#define SETBIT(A,B) A|1<<B

int main(){
    char n,pos;
    printf("Enter a value");
    scanf("%d",&n);
    printf("Enter position");
    scanf("%d",&pos);
    printf("Value after setting %d",SETBIT(n,pos));
}

【问题讨论】:

  • scanf("%d",&amp;n);格式说明符与数据类型不匹配,其他scanf也是。
  • scanf("%d",&amp;n)char n 会产生未定义的行为。 scanf("%d",&amp;pos) 也一样。在实践中,scanf 将 4 字节的数据写入大小为 1 字节的变量中(尽管这些大小通常不受语言标准的规定,但在大多数平台上都是如此)。您需要确定要从键盘扫描的数据类型。使用"%d" - 使用int。对于char - 使用"%c"
  • 请提交格式化代码
  • @WeatherVane:我想你的意思是((A)|1&lt;&lt;(B))
  • @WeatherVane 所有宏参数都应在宏中用括号括起来。 SETBIT(1, 2|4) 的结果可能与 SETBIT(1, 6) 不同

标签: c char int bit


【解决方案1】:

对于*scanf 函数,d 转换说明符期望其对应参数的类型为int *;如果不是这样,则行为是未定义,并且几乎任何结果都是可能的。

如果您想将char 用于posn,则必须在scanf 调用中使用%hhd 而不是%d

【讨论】:

  • 输出还是一样。
猜你喜欢
  • 2019-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多