Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the operator"" do in C++?

How do you call this operator?

Can you use it for things other than the creation of custom literals?

Example usage: (see cppreference)

constexpr long double operator"" _deg ( long double deg )
{
    return deg * 3.14159265358979323846264L / 180;
}
like image 329
User12547645 Avatar asked Oct 27 '22 19:10

User12547645


People also ask

What does %= mean in C?

%= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A.

What is the use of && operator in C?

The logical AND operator ( && ) returns true if both operands are true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool .

What does %d do in C?

%d is a format specifier, used in C Language. Now a format specifier is indicated by a % (percentage symbol) before the letter describing it. In simple words, a format specifier tells us the type of data to store and print. Now, %d represents the signed decimal integer.


1 Answers

The primary usage of this operator"" is the creation of user-defined-literals. From the reference:

Allows integer, floating-point, character, and string literals to produce objects of user-defined type by defining a user-defined suffix.


You can call this operator as you would any other overloaded operator:

std::cout << 42.5_deg;                // with convenient operator syntax
std::cout << operator"" _deg(42.5);   // with an explicit call

Not entirely unrelated: as pointed out in the comments to your question, this example is badly named. It takes in degrees and returns radians, so it should probably be named operator"" _rads. The purpose of UDLs is to have convenient, easy to read syntax, and a function that lies about what it does actively undermines that.


You can use this operator to do pretty much any computation you want (with constraints on the type, and number of the arguments passed in, similar to other operators), for example:

constexpr long double operator"" _plus_one ( long double n )
{
    return n + 1;
}

Though the usage of this operator would still be the same as above.

Here's a demo.

like image 132
cigien Avatar answered Nov 09 '22 01:11

cigien