Why does modulus (%) operator work for char but not for floating types?

[亡魂溺海] 提交于 2019-12-11 13:26:02

问题


#include <stdio.h>

int main()
{
  char c;
  c=10;
  if(c%2==0)
    printf("Yes");
  return 0;
}

The above code prints "Yes". Can someone tell why the modulus operator works for char and int but not for double etc.?


回答1:


You already got comments explaining why % is defined for char: it's defined for all integer types, and in C, char is an integer type. Some other languages do define a distinct char type that does not support arithmetic operations, but C is not one of them.

But to answer why it isn't defined for floating-point types: history. There is no technical reason why it wouldn't be possible to define the % operator for floating-point types. Here's what the C99 rationale says:

6.5.5 Multiplicative operators

[...]

The C89 Committee rejected extending the % operator to work on floating types as such usage would duplicate the facility provided by fmod (see §7.12.10.1).

And as mafso found later:

7.12.10.1 The fmod functions

[...]

The C89 Committee considered a proposal to use the remainder operator % for this function; but it was rejected because the operators in general correspond to hardware facilities, and fmod is not supported in hardware on most machines.

They seem somewhat contradictory. The % operator was not extended because fmod already filled that need, but fmod was picked to fill that need because the committee did not want to extend the % operator? They cannot very well both be true at the same time.

I suspect one of these reasons was the original reason, and the other was the reason for not later re-visiting that decision, but there's no telling which was first. Either way, it was simply decided that % wouldn't perform this operation.



来源:https://stackoverflow.com/questions/25340496/why-does-modulus-operator-work-for-char-but-not-for-floating-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!