简体   繁体   中英

Why does C# implement pre/post-increment/decrement operators for floating point types?

What's so special about adding/subtracting 1 to/from a floating point value that it deserves a dedicated operator?

double a = -0.001234129;
a++; // ? 

I've never felt the need to use such a construction; it looks really weird to me. But if I ever had to, I'd feel much more comfortable with just:

a += 1;

Maybe it's because of my strong C++ background, but to me it makes a variable look like an array indexer.

Is there any reason for this?

The ++ and -- operators operate on all other number types, why make an exception for floating point numbers? To me, that would be the more surprising choice.


Note that C++ also implements these for floating point:

#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
    double a = 0.5;
    cout << a << '\n';
    ++a;
    cout << a << '\n';
    return 0;
}

Output:

0.5
1.5

My guess is that the reason is consistency with C/C++.

I agree with you, that it's kind of weird - the '++' operator has some special meaning for integer values:

  1. It translates to INC assembly instruction,
  2. It represents changing the value by a special amount (ie by the smallest possible amount), and because of this it's used in iterations.

For floating point numbers, however, the value 1.0 is not any special value (from machine point of view). You also shouldn't use it for iterations (in other words: if you're using it you should usually consider using an int) as well as it doesn't have a designated INC assembly instruction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM