Exponentiation operator in C++

Asked

Viewed 2,062 times

4

About a question recently asked and answered: there is some reason - historical or not - why C++ (as well as many other programming languages) does not include an operator for exponentiation?

For example, when I want to calculate 5 to 7.2 I have to do:

#include <cmath>
[...]
resultado=pow(5,7.2);

And if there was an operator op, would simply:

resultado=5 op 7.2;

The answer to this question should not be based solely on personal opinions (these can be discussed in footnote in the comments) but should try to include references that support the possible reasons.

  • Did any help you more? You need something to be improved?

1 answer

4

The probable historical motive is because neither does C. And it does not have, because originally it was not thought to perform many mathematical operations.

Remember that the language was created to write an operating system and not solve scientific problems. Remember that the language aimed to improve the Assembly, who did not possess it as instruction.

In addition, the machines of that time were simple and probably not worth creating an operator. Nor was it a common operation. It was very easy to burst the values that the processor worked naturally, complicating the algorithms in such a way that the function gave in the same.

It has already been discussed the possibility of creating the operator for C++, there are not enough advantages to introduce in the language that is already complicated. It is not as trivial to implement it as it may seem, at least not in a language with this history.

If only the syntax matters, it is possible to create it:

template<typename T>
T operator^(T x, T y) {
    return std::pow(x, y);
}

I put in the Github for future reference.

You need to know if you should, you’re killing the XOR. And keep an eye on the precedence table of it. It might get weird.

  • Nice answer. But wouldn’t it be worth describing a little more (nothing too broad, just a few details and maybe an external reference for more information). :)

  • I think the least important :), I put this example more as a curiosity, because I don’t think I should do this. It is killing the XOR because this is the XOR operator :) Could choose another, could be more restrictive in what can use this operation, but none of this makes much sense, it is better to use the function.

  • Okay, no mistake, no mistake. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.