passing signed char as argument to function's char& failing

Aug 12, 2009 at 3:08am
In Stroustrup's "The C++ Programming Language", exercise 6 of 5.9, I'm to pass an unsigned character and a signed character as arguments for f(char), g(char&) and h(const char&). Here is what I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
void f(char c){}
void g(char& c){}
void h(const char& c){}

int main()
{
	unsigned char uc;

	f(uc); // OK

//	g(uc); // error C2664: 'g' : cannot convert parameter 1 from '
               // unsigned char' to 'char &'
	       // Explanation: The initializer of a "plain" T& must be an 
               // rvalue of type T. uc is a rvalue but its type is
	       // "unsigned char" whereas g()'s type is "char"

	h(uc); // OK, const T& may take a different type.

	signed char sc;

	f(sc); // OK
//	g(sc); // error C2664: 'g' : cannot convert parameter 1 from 
               // 'signed char' to 'char &'
	       // Explanation: The initializer of a "plain" T& must be an 
               // rvaule of type T. sc is a rvalue but its type is
	       // "signed char" whereas g()'s type is "char"

	h(sc); // // OK, const T& may take a different type.

	return 0;
}


In my implementation, char *is* a signed char -- i.e.,
it's range is -128 to 127. So why does g(sc) above fail? Is type checking
of references so strict that it ignores the implementation of char?
Aug 12, 2009 at 3:32am
Is type checking of references so strict that it ignores the implementation of char?
Yes. T != unsigned T != signed T.
Aug 12, 2009 at 5:51pm
Is this for the sake of portability? In other words, isn't the rule best stated as:

T not necessarily = signed T

since on my specific implementation,

T == signed T

but if the compiler allowed the above g(sc) it would fail on another implementation where

T == unsigned T?

Topic archived. No new replies allowed.