Search code examples
cfloating-pointoperatorsmodulus

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


#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.?


Solution

  • 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.