views:

430

answers:

4

I've seen this unsigned "typeless" type used a couple of times, but never seen an explanation for it. I suppose there's a corresponding signed type. Here's an example:

static unsigned long next = 1;
/* RAND_MAX assumed to be 32767 */
int myrand(void) {
    next = next * 1103515245 + 12345;
    return((unsigned)(next/65536) % 32768);
}
void mysrand(unsigned seed) {
    next = seed;
}

What I have gathered so far:
- on my system, sizeof(unsigned) = 4 (hints at a 32-bit unsigned int)
- it might be used as a shorthand for casting another type to the unsigned version:

signed long int i = -42;
printf("%u\n", (unsigned)i);

Is this ANSI C, or just a compiler extension?

+19  A: 

unsigned really is a shorthand for unsigned int, and so defined in standard C.

Martin v. Löwis
+6  A: 

unsigned means unsigned int. signed means signed int. using just unsigned is a lazy way of declaring an unsigned int in C. Yes this is ANSI.

Polaris878
+1  A: 

in C, unsigned is a shortcut for unsigned int.

You have the same for long that is a shortcut for long int

And it is also possible to declare a unsigned long (it will be a unsigned long int).

This is in the ANSI standard

ThibThib
+5  A: 

Historically in C, if you omitted a datatype "int" was assumed. So "unsigned" is a shorthand for "unsigned int". This has been considered bad practice for a long time, but there is still a fair amount of code out there that uses it.

anon
I wasn't aware that it was bad practice. Is there a rationale for this? `long` instead of `long int` is very common so I'm not sure why `unsigned` instead of `unsigned int` wouldn't be acceptable.
Charles Bailey
@Charles Bailey: these days - at least if you are being pragmatic rather than formal - long, int, short and char are considered to be different data types as they can be different sizes) with unsigned (and the default, signed) being a qualifier. Thus you would tend to use "unsigned int" in the same way you would use "unsigned long" or "unsigned char" (and it makes it clear that you didn't just miss off the int). The int in "long int" or "short int" is superfluous.
Dipstick