Saturday, October 19, 2013

climits and minimum or maximum values

This code does the following:

Notes on syntax etc:

  • sizeof operator puts brackets around type - e.g. sizeof (int) - but not around variables - e.g. sizeof n_short

Note that uses expressions such as "#define INT_MAX 32767" - which, on inclusion in the header file, acts as a kind of global find and replace for the values in the #define directive. You can use your own symbolic constants using the #define directive, but this is a relic of C. The better C++ method is to use const.

If you define a variable but don't initialize it then use it in a function the value is indeterminate and ends up as the value at whatever memory location you happen to have at that time.

#include <iostream>
#include <climits>

using namespace std;

int main()
{
    using namespace std;
    int n_int = INT_MAX;
    short n_short = SHRT_MAX; //these symbols defined in climits file
    long n_long = LONG_MAX;
    long long n_llong = LLONG_MAX;

    //sizeof operator yields size of type or of variable - NOT the maximum value it looks like
    cout << "int is " << sizeof (int) << " bytes" << endl;
    cout << "short is " << sizeof n_short << " bytes" << endl;
    cout << "long is " << sizeof n_long << " bytes" << endl;
    cout << "long long is " << sizeof n_llong << " bytes" << endl;
    cout << endl;

    cout << "maximum values" << endl;
    cout << "int: " << n_int << endl;
    cout << "short: " << n_short << endl;
    cout << "long: " << n_long << endl;
    cout << "long long: " << n_llong << endl;

    cout << "minimum int value: " << INT_MIN << endl;
    cout << "bits per byte: " << CHAR_BIT << endl;

    return 0;
}

No comments:

Post a Comment