what does "1u" mean? when we use it?

Mar 27, 2008 at 3:40am
hi all:
I found some code for insertion sort like this:
1
2
3
4
5
6
7
8
9
//...code
	for (unsigned int i = 1; i < n; ++i)
	{
		for (unsigned int j = i; j > 0 && array[j - 1u] > array[j]; --j)
		{
			swap(array[j], array[j - 1u]);
		}
	}
//...code 

what does the "1u" mean? And when should we use it instead of just use "1"?
Mar 27, 2008 at 4:14am
It means the digit, associated with it, is unsigned.

The use of unsigned varies upon necessity. Some programs are better controlled when using unsigned data types. A good habit is to use unsigned digits to refer array indexes. This ensures that you'll never go a size smaller than 0.

There are also some cases that even if unsigned data types are used, a negative value is still plausible. This is because most computers work with two's complement numbering system.
Mar 27, 2008 at 4:15am
I also have to add that unsigned digits have larger, NOT MORE, representation of counting numbers.
Mar 27, 2008 at 6:25am
Thanks a lot for your reply!
Mar 27, 2008 at 6:35am
There's a difference between declaring an unsigned variable, and an unsigned literal. The former is used to make it easier to check values. e.g:
1
2
3
4
5
6
// With signed int:
if (i < 0 || i > max)
  // error
// With unsigned int:
if (i > max)
  // error 

OR to make it possible to use more positive numbers (2147483648-4294967296 for 32 bit integers).

The latter is really only necessary when need a literal number in the mentioned range:
1
2
3
unsigned int i = 3000000000U; // Needed
unsigned int i = 2000000000U; // Not really necessary
unsigned int i = 2000000000;  // because this is fine 

Last edited on Mar 27, 2008 at 6:36am
Topic archived. No new replies allowed.