I am trying find the sizes for data types but i am not allowed to use the "sizeof()" method. here is what i need to do, but without the "sizeof()"
cout<<"Size of type char is "
<<sizeof(char);
thank you
I am trying find the sizes for data types but i am not allowed to use the "sizeof()" method. here is what i need to do, but without the "sizeof()"
cout<<"Size of type char is "
<<sizeof(char);
thank you
Must be a homework from a rather odd teacher to solve a rather pointless problem in an unusual way.
What else are you not allowed to use?
How about
Code:unsigned char ch = ~0; int count = 0; while ( ch != 0 ) { count++ ; ch >>= 1; }
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
What does the ~0 do ? I had thought that ~ (tilde) was to be used only for destructors.Code:unsigned char = ~0
First hear, then understand, and then, leaving all distractions, shut your mind to outside influences and devote yourself to developing the truth within you.
the ~ reverses the bits, so 10001010 tilded would be 01110101.
It's good since it can find the max value of a data type from the min if 00000000 is 0 then tilded it's 11111111 would be the max value, unsigned it would be 255.
My Avatar says: "Stay in School"
Rocco is the Boy!
"SHUT YOUR LIPS..."
you could use pointer math...
char *c = 0;
c++;
int * i = 0;
i++;
long *l = 0;
l++;
double *d = 0;
d++;
cout << "sizeof a char is " << (int)c << endl;
cout << "sizeof an int is " << (int)i << endl;
cout << "sizeof a long is " << (int)l << endl;
cout << "sizeof a double is " << (int)d << endl;
aren't I clever?
Last edited by FillYourBrain; 11-15-2002 at 10:35 AM.
"You are stupid! You are stupid! Oh, and don't forget, you are STUPID!" - Dexter
That done be the mostest intelligents answer I've been seen.
My Avatar says: "Stay in School"
Rocco is the Boy!
"SHUT YOUR LIPS..."
Heh - two more methods
Code:#include <iostream> #include <cstdlib> using namespace std; // difference between adjacent members of an array #define T1(type) { \ type d[2]; \ cout << "sizeof(" #type ") is " << (int)&d[1] - (int)&d[0] << endl; \ } // difference between adjacent members of a struct // assumes that a struct containing a single type is always packed #define T2(type) { \ struct foo { type a; type b; }; \ cout << "sizeof(" #type ") is " << offsetof(foo,b) << endl; \ } int main ( ) { T1(char); T2(char); T1(short); T2(short); T1(int); T2(int); T1(double); T2(double); return 0; }
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I told you I be smart!
"You are stupid! You are stupid! Oh, and don't forget, you are STUPID!" - Dexter