Why would you want to use these statements in a c++ program? |
Internally numbers are stored in a binary representation.
256 = 2*2*2*2*2*2*2*2 = 8 bits = 1 byte = 256 different combinations = 0 to 255(1 to 256) = 10000000 (binary representation)
1 bit is either 0 or 1, gives it 2 possible combinations.
However, if grouped together with other bits, the total possible combinations increases by a power of 2(^2), as their added (because each bit has two possible combinations).
Now an
int
of signed or unsigned, would in both cases consume same amount of bits.
But in order to have and
int
perform 'negative' values but still occupy the same amount of bits, you would have to sacrifice some of it's positive numbers. Because after all you still occupy, the same amount of bits/combinations.
To summarize: By using a 'signed type', you would be able to calculate on 'negative' values, but you'd lose (in the case of c++) 50% of it's 'positive' range.
This means that an 'unsigned type' is able to calculate on twice the amount of 'positive' numbers than a 'signed type'.
how do they help the program out in any way? Please explain and provide examples if possible. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
/*Say you have an array with 256(0 to 255) different elements.
*Now instead of allocating an integer(which consumes, way more space than we need)
*You could just declare a variable of unsigned char to cycle through the elements in a loop.
*And in the process same that extra space(and processing power used to allocate it) for something else, making your code faster and more efficient.
**/
int main(){
short array[256];
//by using an unsigned char, as opposed to an int you'd save yourself
//3 bytes.
for(unsigned char x = 0;x<256;++x){
array[x] = 0;
}
return 0;
}
|
I hope this helps to some extent.
But i recommend to you that you google the following:
1. stack c++,
2. binary number base,
3. bytes,
4. c++ datatypes.
2,3, and 4 are especially useful to know about when you are dealing with very large numbers(numbers that begin reaching the max range of a datatype).