AlexaGIS
AlexaGIS

Reputation: 21

C++: Can a + or - tell the compiler a value should be an int?

I'm a beginner with C++ so this may seem like a silly question. Please humour me!

I was using static_cast<int>(numeric_limits<unsigned_char>::min()) and ::max() (according to this post), but also found here that a + or - sign can be used before the numeric_limits to achieve the same result. Am I correct in assuming that the +/- is basically just telling the compiler that the next thing is a number? Why would I use that as opposed to a static_cast?

Upvotes: 2

Views: 98

Answers (2)

Jon Reeves
Jon Reeves

Reputation: 2586

The + sign you're seeing on that page is referred to as the "unary plus" operator. You should probably read up on arithmetic operators here to get a better understanding of what's happening.

That page has the following things to say about unary plus:

The built-in unary plus operator returns the value of its operand. The only situation where it is not a no-op is when the operand has integral type or unscoped enumeration type, which is changed by integral promotion, e.g, it converts char to int or if the operand is subject to lvalue-to-rvalue, array-to-pointer, or function-to-pointer conversion.

Unlike binary plus (i.e. where you would have two operands), unary plus is a slightly less common operator to see used in practice, but to be clear, there is nothing particularly special about it. Like other arithmetic operators, it can be overloaded, which means it's hard to say "universal" things about its behavior. You need to know the context in which it's being used to be able to predict what it's going to do. Start with a firm understanding of the various operators available and work your way down to this specific example.

Upvotes: 4

eerorika
eerorika

Reputation: 238401

Am I correct in assuming that the +/- is basically just telling the compiler that the next thing is a number?

No.

+ and - are simply artihmetic operators. For numeric operands, the unary minus operator changes the sign of the right hand operator and the unary plus operator doesn't change the sign.

The reason why the result is int even though the operand was unsigned char is because all operands of all arithmetic operators are always converted to int (or to unsigned int if all values of the operand's type aren't representable by int) if they were of lower rank. This special conversion is called integer promotion.

Why would I use that as opposed to a static_cast?

It's less characters to type. If that's appealing to you, then maybe you would use it for that purpose. If it isn't, then perhaps you should use static cast instead.

Upvotes: 4

Related Questions