About climits

I have this sample code from a book:



// limits.cpp -- some integer limits
#include <iostream>
#include <climits> // use limits.h for older systems

int main()
{
using namespace std;

int n_int = INT_MAX; // initialize n_int to max int value
short n_short = SHRT_MAX; // symbols defined in limits.h file
long n_long = LONG_MAX;

// sizeof operator yields size of type or of variable
cout << "int is " << sizeof (int) << " bytes." << endl;
cout << "short is " << sizeof n_short << " bytes." << endl;
cout << "long is " << sizeof n_long << " bytes." << endl << endl;
cout << "Maximum values:" << endl;
cout << "int: " << n_int << endl;
cout << "short: " << n_short << endl;
cout << "long: " << n_long << endl << endl;
cout << "Minimum int value = " << INT_MIN << endl;
cout << "Bits per byte = " << CHAR_BIT << endl;

cin.get();
return 0;
}


I tried commenting line "#include <climits>". I expected that it wouldn't compile but it did. I thought climits defined the values for INT_MAX, CHAR_BIT, SHRT_MAX and others. But why did it compile. I am probably misunderstanding something; could someone explain it to me, please? Thanks!
closed account (z05DSL3A)
climits (limits.h) would have been included via iostream.
Hi Grey Wolf,

Thanks, that's what I thought. Does that mean I don't have to include climits or is it a good idea to include it?

One last question. I opened up my iostream file and I cannot see any reference to climit. Or am I opening the wrong file? When I search for iostream files, a number of files appears iostream.h, iostream.cpp, and some with no extension. I know you're right but I just want to see it for myself. Thanks!
Last edited on
closed account (z05DSL3A)
Then that means I don't have to include climits...

You don't have to, but it is good practice to include the headers you want and not rely on 'accidental' inclusion.

If you look in the iostream file you may find that it includes other header files, which in turn include other header files, until you finally find the one that includes climit or limit.h. The files you are interested in have no extension or a .h extension.
Thanks Grey Wolf!
More in the spirit of C++ (since you are using iostreams) would be to use (for example):

1
2
3
4
5
6
#include <limits>
#include <iostream>

int main() {
   std::cout << "max int = " << std::numeric_limits<int>::max() << std::endl;
}

Topic archived. No new replies allowed.