Hans <Ha**@replyingr ouptoavoidspam. com> writes:
[...]
If I try this:
#include <stdio.h>
int main() {
char c = -1; // 129 unsigned and -1 signed right?
// convert it to a value between 0 - 255 for array Lookup
unsigned int arrayIndex = (unsigned int) c;
if (arrayIndex < 0)
printf("ArrayIn dex still negative after conversion to unsigned int
%d\n",arrayInde x);
else
printf("Unsigne d representation is OK for ArrayIndex=%d\n ",arrayInde x);
}
The output is: "ArrayIndex still negative after conversion to unsigned
int -1"
Why did you cross-post to comp.lang.c and comp.lang.c++? There's
nothing specific to C++ in your program (except possibly the comments
and the missing return statement). Remember, C and C++ are two
different languages.
It's best to use /*...*/ comments when posting to comp.lang.c. Not
all C compilers support // comments, and they're more vulnerable to
being split across lines by news software.
You should also keep your source lines relatively short. The string
literal in your first printf() was split.
Assuming CHAR_BIT==8 (and UCHAR_MAX==255) , the unsigned equivalent of
-1 is 255, not 129.
The cast on the initialization of ArrayIndex is superfluous; the value
is going to be converted to unsigned int anyway.
You should have a "return 0;" at the end of your main program. It's
not strictly required in C99 or C++, but it is in C90 (if you don't
want to return an undefined exit status).
You're using the wrong printf format for arrayIndex. The variable is
of type unsigned int; you need to use "%u", not "%d".
Having said all that, I can't reproduce the problem you describe. The
value assigned to arrayIndex is going to change depending on whether
"plain" char is signed or unsigned. If it's unsigned, c is set to
UCHAR_MAX (typically 255), and arrayIndex is set to the same value.
If plain char is signed, c is set to -1, and arrayIndex is set to
UINT_MAX (typically 4294967295 on 32-bit systems) -- which is likely
to be printed as "-1" if you use the incorrect "%d" format. (I think
C++ behaves the same way as C.)
If you want to use a char to store a value that has to be
non-negative, use an unsigned char, not a plain char. Plain char may
happen to work on your system, but your code is likely to break on
others (and it's more difficult to determine what the code is going to
do if you leave the signedness up to the compiler).
By using (unsigned) char as an array index, you're limiting the index
values to 255 (potentially more on exotic systems with CHAR_BIT > 8,
but 255 is the portable limit). Not knowing anything about your
application, I can't guess whether that's a potential problem.
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.