one question.
does it make any difference between char and unsignedchar if I were to use the variable as a bit pattern? what i want is only the pattern
ah, one more question about char and unsignedchar
when i use the static_cast<unsignedchar *>(data) instead of (unsignedchar *)data for data is a char *, i get an error. is that the difference between these two type castings, that the first one is safer?
For your first question. There is actually a difference; I am not familiar with what it is exactly; but I have seen answers vary when converting between them and bit streams.
You want to use an unsigned char.
The static cast will probably give you an error because there is a potential to lose information when converting to an unsigned char from a signed char. If your going to be doing bit manipulation; use unsigned.
since the object I use only give a char * as the return value, i cannot do anything about it. i just want to make sure of whether unsigned char is any safer than the char.
i tried to assign the char through hexadecimal and it gave no different to unsigned char, except if the number greater then 0x7F i got a warning. that was so might because the range for signed char was already exceeded i.e +127 or 0x7F.
one way to get rid of the warnig is to casting the hexadecimal number like this char a = (char)0xFF. it works. i know it means we are telling the compiler that we know what we are doing.
btw, thanks for replies
unsigned char is safer than a char as a bit pattern.
That is:
unsignedchar a = 0xFF;
does not produce a warning.
Your cast just tells the compiler to shut up about truncating the constant value to 0x7F so it will fit in the char. Now your code does not match what is happening. The cast has destroyed the type safety of your program.
You should not be casting in C++ unless you have a precise reason that forces you to do it and truncating data is not one of those reasons.
In C, due to weaknesses in the language, casting is a way of life. Many C programmers carry their bad casting habits into C++ and end up writing C programs with their C++ compilers.
In any case, do not use the C cast form in C++:
char a = (char)0xFF; //C cast form
Use one of the C++ cast forms instead:
char a = static_cast<char> (0xFF);
The C++ cast forms have been specfically designed to be ugly so they stand out in your code. The more of these you have the worse your code.
thanks for the tips weaknessforcats. It does fit me, the bad habits of C programmers. I learned much C and so little about C++. seriously, why are we still using C when C++ is safer? I wonder about this
@akmalnuenberg: C is still widely used because it has alot of know behaviours (especially around memory management). C is also faster than OO-C++ because it doesn't have the overhead of OO. There are a fair few articles around by Linus Torvalds on why he uses C over C++ for Linux.