Integer promotion?

  • Thread starter Frederick Gotham
  • Start date
F

Frederick Gotham

On my system, the following doesn't work properly:

#define UCHAR_MAX ( ~( (unsigned char)0 ) )


Could someone please explain why it doesn't work? My hunch is that it has
something to do with integer promotion.


Since the previous example doesn't work, why is it that the following
does?

template<class AnyUnsignedIntegerType>
AnyUnsignedIntegerType MaxVal()
{
return ~AnyUnsignedIntegerType(0);
}

#include <iostream>

int main()
{
std::cout << (unsigned long) MaxVal<unsigned char>() << "\n\n";

/* Cast required so it prints as a number rather
than as a character */
}
 
V

Victor Bazarov

Frederick said:
On my system, the following doesn't work properly:

#define UCHAR_MAX ( ~( (unsigned char)0 ) )


Could someone please explain why it doesn't work? My hunch is that it
has something to do with integer promotion.

Macros have no type. If you try using your 'UCHAR_MAX' macro (is there
a reason you used the standard name? You know you're not allowed to,
right?) the 0 is promoted to 'int', then one's complement is obtained,
then the value "all bits set" is used. If your int is 16 bits, you get
65535.
Since the previous example doesn't work, why is it that the following
does?

template<class AnyUnsignedIntegerType>
AnyUnsignedIntegerType MaxVal()
{
return ~AnyUnsignedIntegerType(0);
}

#include <iostream>

int main()
{
std::cout << (unsigned long) MaxVal<unsigned char>() << "\n\n";

/* Cast required so it prints as a number rather
than as a character */
}

'MaxVal' returns a value of a particular type (the one you instantiated
it with). Whatever the value is inside in the 'return' statement, it
gets converted (in your case most likely truncated) to 'unsigned char'.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,123
Latest member
Layne6498
Top