Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the assignment of ~0u to a variable mean in C++? [duplicate]

Tags:

c++

I understand 0u means 0 unsigned, but what does the ~ at the beginning mean? Does it signify inversion in this case or does it mean something else?

like image 303
ryeager Avatar asked Oct 24 '14 19:10

ryeager


People also ask

What does 0u mean in C?

Much like 0L defines 0 as a long, 0u defines 0 as an unsigned int ( uint ).

What does %U mean in C?

An unsigned Integer means the variable can hold only a positive value. This format specifier is used within the printf() function for printing the unsigned integer variables. Syntax: printf(“%u”, variable_name); or.

What does '~' do in C?

In mathematics, the tilde often represents approximation, especially when used in duplicate, and is sometimes called the "equivalency sign." In regular expressions, the tilde is used as an operator in pattern matching, and in C programming, it is used as a bitwise operator representing a unary negation (i.e., "bitwise ...

What does =+ mean in C++?

The statement that =+ is assignment (equivalent to plain = operator), while += increases a variable's value by a certain amount, is INCORRECT. x += y as well as x =+ y will BOTH have the same effect (that is, both of these will cause the new value of x to be the old value of x + y).


1 Answers

It indicates bitwise not; all bits in the integer will be flipped, which in this case produces a number where all bits are 1.

Note that since it is unsigned, if the integer is widened during assignment the extended bits would be 0. For example assuming that unsigned short is 2 bytes and unsigned int is 4:

unsigned short s = ~0u; // 0xFFFF unsigned int i = s;     // 0x0000FFFF 

If you need to invert the bits of some generic numeric type T then you can use the construct ~(T(0)).

like image 158
cdhowie Avatar answered Sep 23 '22 21:09

cdhowie