-
Memory usage
I have to write a program for class and i have to write it to figure out the maximum space allowed for an integer variable. Can anyone help me or direct me to a web page with some info??
Is there like 2 different amounts depending on what language u use?
Thanks
-
It depends on the computer, and operating system.
Use the sizeof( ) keyword, to find the size of an int.
a char is usually 1 byte
a short is usually 2 bytes
a long is usually 4 bytes.
an int can be 2 or 4 bytes, it is usually 4 on newer machines/os'es
Code:
#include <iostream>
using namespace std;
int main()
{
cout << "Size of char is " << sizeof(char) << endl;
cout << "Size of short is " << sizeof(short) << endl;
cout << "Size of long is " << sizeof(long) << endl;
cout << "Size of int is " << sizeof(int) << endl;
cout << "Size of float is " << sizeof(float) << endl;
cout << "Size of double is " << sizeof(double) << endl;
return 0;
}
Gave me this output
Size of char is 1
Size of short is 2
Size of long is 4
Size of int is 4
Size of float is 4
Size of double is 8
-
What is the relationship though? Or i mean what could you write to calculate that amount? Besides using the size command. Thats why i have to do.
-
a char is 1 Byte which is 8 bits.
If you have 8 bits then you have 2^8 possible values. 2^8 = 256
this is 0..255 unsigned
or it is -128..127 signed
here is a general formula for range of values
range = pow( 2 , sizeof(type)*8 ); //range = 2^(#bytes*8 bits/byte)
Then the min value for an unsigned type is 0
and the max for an unsigned type is range -1;
The min value for a signed type is range/2;
the max value for a signed type is range/2 -1;
you should be able to figure out the rest