Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why or why not should I use 'UL' to specify unsigned long?

Tags:

c++

ulong foo = 0;
ulong bar = 0UL;//this seems redundant and unnecessary. but I see it a lot.

I also see this in referencing the first element of arrays a good amount

blah = arr[0UL];//this seems silly since I don't expect the compiler to magically
                //turn '0' into a signed value

Can someone provide some insight to why I need 'UL' throughout to specify specifically that this is an unsigned long?

like image 664
BuckFilledPlatypus Avatar asked Aug 13 '09 18:08

BuckFilledPlatypus


People also ask

Is unsigned int better to use?

Given the above, the somewhat controversial best practice that we'll advocate for is to avoid unsigned types except in specific circumstances. Favor signed numbers over unsigned numbers for holding quantities (even quantities that should be non-negative) and mathematical operations.

What is unsigned long?

Unsigned long variables are extended size variables for number storage, and store 32 bits (4 bytes). Unlike standard longs unsigned longs won't store negative numbers, making their range from 0 to 4,294,967,295 (2^32 - 1).

What does UL mean in C language?

Unsigned constants are written with a terminal u or U , and the suffix ul or UL indicates unsigned long . Floating-point constants contain a decimal point ( 123.4 ) or an exponent ( 1e-2 ) or both; their type is double , unless suffixed. The suffixes f or F indicate a float constant; l or L indicate a long double .


2 Answers

void f(unsigned int x)
{
//
}

void f(int x)
{
//
}
...
f(3); // f(int x)
f(3u); // f(unsigned int x)

It is just another tool in C++; if you don't need it don't use it!

like image 125
Khaled Alshaya Avatar answered Nov 16 '22 01:11

Khaled Alshaya


In the examples you provide it isn't needed. But suffixes are often used in expressions to prevent loss of precision. For example:

unsigned long x = 5UL * ...

You may get a different answer if you left off the UL suffix, say if your system had 16-bit ints and 32-bit longs.

Here is another example inspired by Richard Corden's comments:

unsigned long x = 1UL << 17;

Again, you'd get a different answer if you had 16 or 32-bit integers if you left the suffix off.

The same type of problem will apply with 32 vs 64-bit ints and mixing long and long long in expressions.

like image 43
Brian Neal Avatar answered Nov 15 '22 23:11

Brian Neal