这个C程序的输出是什么,以及它是如何工作的?

huangapple go评论68阅读模式
英文:

What is the output of this C program and how does it work?

问题

上述代码的输出及简要解释?由于res类型应该提升为整数,我认为它会打印-212,但实际输出是-84。

英文:
#include <stdio.h>

int main()
{
    signed char a = 200;
    signed char b = 3;
    signed char c = 2;
    signed char res = (a * b)/c;
    
    printf("%d\n", res);

    return 0;
}

Output of the above code with brief explanation? since the res type should promote to integer, I thought that it would print -212, but the actual output is -84.

答案1

得分: 6

根据ISO C11标准的§6.3.1.3 §3,假设您在一个SCHAR_MAX小于200的平台上(这在大多数平台上都是如此),那么以下代码行:

signed char a = 200;

将会将一个实现定义的值写入a或引发一个实现定义的信号。大多数平台将从200中减去值UCHAR_MAX+1。假设UCHAR_MAX的值为255(在大多数平台上都是如此),这意味着它将将值-56写入a

因此,以下代码行:

signed char res = (a * b)/c;

等效于:

signed char res = (-56 * 3)/2;

这等效于:

signed char res = -84;

值得注意的是子表达式:

(a * b)

将计算为-168,即使该值小于SCHAR_MIN。这是因为结果的类型是int。作为通常的算术转换的一部分,两个操作数都被提升为int,这意味着结果也是int

由于结果-168在分配给signed char之前被除以2,所以它将具有值-84,这在ISO C标准中被保证可以由signed char表示(SCHAR_MIN被保证等于或小于-127)。

英文:

Assuming that you are on a platform on which SCHAR_MAX is smaller than 200 (which is the case on most platforms), then, according to §6.3.1.3 ¶3 of the ISO C11 standard, the line

signed char a = 200;

will write an implementation-defined value to a or raise an implementation-defined signal. Most platforms will simply subtract the value UCHAR_MAX+1 from 200. Assuming that UCHAR_MAX has the value 255 (which is the case on most platforms), this means that it will write the value -56 to a.

The line

signed char res = (a * b)/c;

is therefore equivalent to:

signed char res = (-56 * 3)/2;

This is equivalent to:

signed char res = -84;

It is worth noting that the sub-expression

(a * b)

will evaluate to -168, even if that value is smaller than SCHAR_MIN. This is because the type of the result is int. As part of the usual arithmetic conversions, both operands get promoted to int, which means that the result is also int.

Since the result -168 gets divided by 2 before being assigned to a signed char, it will have the value -84, which is guaranteed by the ISO C standard to be representable by a signed char (SCHAR_MIN is guaranteed to be equal to or smaller than -127).

答案2

得分: 2

表达式(a * b)/c似乎会引起算术溢出,因为有符号字符的值只能在大多数平台上从-128127之间,而由于溢出,a的值为-56-56*3等于-168-168/2等于-84
但在计算中它对int值执行操作,所以没有溢出。

英文:

The expression (a * b)/c seems to cause arithmetic overflow because signed characters can have values only from -128 to 127 (on most platforms), and the value of a is -56 because of the overflow. and -56*3 is -168 and -168/2 is -84.
but in the calculation it performs operations on int values, so there's no overflow.

huangapple
  • 本文由 发表于 2023年6月1日 13:32:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76378899.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定