0

I am trying to implement the mod operator on a double that is temporarily converted to an integer (rounded), but the compiler (clang) doesn't seem to like that and returns the error: assignment to cast is illegal, lvalue casts are not supported. For example, in this snippet

double a;
int b;
(int)a %= b;

Is there a way to get around this limitation?

Josh Simani
  • 107
  • 10

1 Answers1

2

What you are doing is illegal. Saying (int)a = ... is illegal because you cannot cast a to an integer in this way. You must cast it on the right hand side of the assignment.

If you really wanted to do this, you could say:

double a;
int b;
a = (double)((int)a % b); /* Casting to a double at this point is useless, but because a is a double-type, the result of the modulus it will be implicitly casted to a double if you leave out the explicit cast. */

I would advise assigning the modulus result to a new int variable, but that is your choice to make.


Edit: Here is an example of this: http://ideone.com/tidngT

Also, it is worth noting that casting a double to an int does not round it, but rather, it just truncates it. And, if the value of your double is higher than the range of an int, then this can produce undefined behavior.

Spencer D
  • 3,376
  • 2
  • 27
  • 43