1

I'm new to C and have seen code such as (unsigned)b

Does that imply that b will be an unsigned int? Or what type does it imply?

RustyShackleford
  • 25,262
  • 6
  • 22
  • 38

2 Answers2

3

b will be whatever type it was to begin with. That doesn't change

(unsigned)b will evaluate as whatever value b is, but that is subject to the cast to unsigned, which is synonymous with unsigned int.

How that happens depends entirely on the type of b to begin with, whether that type is convertible to unsigned int, and whether the value contained therein falls unscathed between 0...UINT_MAX or not.

Ex:

#include <stdio.h>

void foo(unsigned int x)
{
    printf("%u\n", x);
}

int main()
{
    int b = 100;
    foo((unsigned)b); // will print 100

    char c = 'a';
    foo((unsigned)c); // will print 97 (assuming ASCII)

    short s = -10;    // will print 4294967286 for 32-bit int types 
                      // (see below for why)
    foo((unsigned)s);

    // won't compile, not convertible
    //struct X { int val; } x;
    //foo((unsigned)x);
}

The only part of this that may raise your eye brow is the third example. When a value of a convertible type to an unsigned type is out of the unsigned type's range (ex: negative values are not same-value representable with any unsigned target types), the value is converted by repeatedly added the maximum value representable by the unsigned target plus-one to the out-of-range value until such time as it falls within the valid range of the unsigned type.

In other words, because -10 is not within the valid representation of unsigned int, UINT_MAX+1 is added to -10 repeatedly (only takes once in this case) until the result is within 0...UINT_MAX.

Hope that helps.

WhozCraig
  • 65,258
  • 11
  • 75
  • 141
1

unsigned is a short of unsigned int

signed is a short of signed int

long is the short of long int

long long is the short of long long int

short is the short of short int