3 ms·
Why do programming languages implement the unary operator “+”?
It's practically and aesthetically useless for me. I've never used it.
- waynecochran 6y agoCompleteness. Also, sometimes syntactically nice to emphasize the sign: double pos = +foo; double neg = -bar; Occasionally useful in auto-generated code. There are strange edge cases you might find it useful. "I've never used it" is a bad judgment of its general usefulness.
- unlimiter 6y agoI'm designing a minimalist language and I'm not sure if I "need" to implement it while looking at it from a minimalist perspective. But I mostly won't until I find a good enough argument.
- waynecochran 6y agoAlmost 0 overhead to implement. Same precedence as unary '-' so extra parsing is trivial. No need to generate as AST for it.
- Someone 6y agohttps://stackoverflow.com/a/7611586 https://stackoverflow.com/a/7611586 claims K&R says it was added for symmetry, but in C and C++ it ¿nowadays? also converts char to int. That can be useful to print the values of characters (std::cout << c outputs a char, std: court << +c its value). In JavaScript: to convert strings to numbers. In Python: to assert that a value is numeric (throws a TypeError if it isn’t). In Perl: among others, replaces an initial ‘-‘ in a string by a ‘+’ and vice versa (https://perldoc.perl.org/perlop.html#Symbolic-Unary-Operators https://perldoc.perl.org/perlop.html#Symbolic-Unary-Operator.... See also https://perlmaven.com/the-magic-unary-plus https://perlmaven.com/the-magic-unary-plus for more power/weirdness)