What is the reason for double negation - (- n)?

I am looking at the code for outdated code, and I saw something like

char n = 65; char str[1024]; sprintf(str, "%d", -(-n)); 

Why did the author (no longer present) write -(-n) , and not just n ? Wouldn't --n ?

+2
source share
1 answer

First of all, it should be noted that --n actually reduces n by 1 and evaluates a new value with type char ; therefore he does something very different from -(-n) . Do not change the code for this!

-n performs unary negation of n and is also an expression of type int due to the rules of promotion of type C. Additional negation returns it to its original value, but with type int saved.

So, -(-n) is actually a detailed way of writing +n , which is often a non-operator, but in this case it converts the type n to int .

I suspect that the author is protecting himself from erroneous refactoring, and they were concerned about the mismatch of the argument type with the format specifier %d .

But in this particular case, it does not matter: sprintf will automatically advance the char type to int , so it’s completely safe to write

sprintf(str, "%d", n);

Also consider reducing the size of the str buffer if this is "real" code, and consider using the more secure snprintf option.

(As a concluding remark, note that double negation can lead to overflow with an integral type sign, so use it with caution.)

+13
source

All Articles