Code is unable to pick the macro declared - c++

In the code below, the output values are not as defined in macro , is that because the values have to be available before pre processor stage?
#define INT_MAX 100
#include <iostream>
using namespace std;
int main()
{
int x = INT_MAX;
x++;
cout<<x<<INT_MAX;
}
Result is -2147483648

There is a macro named INT_MAX defined in limits.h. I assume that iostreamincludes limits.h and overwrites your own definition of INT_MAX.
This causes an integer overflow at x++ because INT_MAX is the largest value that can be represented by an integer.

What is happening is that after you are defining INT_MAX yourself, you are including iostream. That pulls in limits.h which redefines INT_MAX to be the maximum available 32-bit int - see http://www.cplusplus.com/reference/climits. Incrementing an int with the maximum value is undefined, but wraps around to the minimum possible int value on most CPU architecture/compiler combinations.
Depending on your compiler warning level, you should be getting a warning about INT_MAX being redefined. If you define it to 100 after the include statement, you should get 101.
Redefining macros provided by the standard library tends to lead to confusion, so I recommend you to pick a different name for your macro.

Related

Why does this c++ boolean return false [duplicate]

Had been going through this code:
#include<cstdio>
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {1,2,3,4,5,6,7};
int main()
{
signed int d;
printf("Total Elements in the array are => %d\n",TOTAL_ELEMENTS);
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
return 0;
}
Now obviously it does not get into the for loop.
Whats the reason?
The reason is that in C++ you're getting an implicit promotion. Even though d is declared as signed, when you compare it to (TOTAL_ELEMENTS-2) (which is unsigned due to sizeof), d gets promoted to unsigned. C++ has very specific rules which basically state that the unsigned value of d will then be the congruent unsigned value mod numeric_limits<unsigned>::max(). In this case, that comes out to the largest possible unsigned number which is clearly larger than the size of the array on the other side of the comparison.
Note that some compilers like g++ (with -Wall) can be told to warn about such comparisons so you can make sure that the code looks correct at compile time.
The program looks like it should throw a compile error. You're using "array" even before its definition. Switch the first two lines and it should be okay.

Why can the std::cout display value less than the minimum value of a float? [duplicate]

When I run this code:
#include <limits>
#include <cstdio>
#define T double
int main()
{
static const T val = std::numeric_limits<T>::min();
printf( "%g/2 = %g\n", val, val/2 );
}
I would expect to see an unpredictable result.
But I get the correct answer:
(16:53) > clang++ test_division.cpp -o test_division
(16:54) > ./test_division
2.22507e-308/2 = 1.11254e-308
How is this possible?
Because min gives you the smallest normalized value. You can still have smaller denormalized values (see http://en.wikipedia.org/wiki/Denormalized_number).
Historical reasons. std::numeric_limits was originally built
around the contents of <limits.h> (where you have e.g.
INT_MIN) and <float.h> (where you have e.g. DBL_MIN).
These two files were (I suspect) designed by different people;
people doing floating point don't need a separate most positive
and most negative value, because the most negative is always the
negation of the most positive, but they do need to know the
smallest value greater than 0. Regretfully, the values have the
same pattern for the name, and std::numeric_limits ended up
defining the semantics of min differently depending on
std::numeric_limits<>::is_integer.
This makes template programming more awkward, you keep having to
do things like std::numeric_limits<T>::is_integer ? std::numeric_limits<T>::min() : -std::numeric_limits<T>::max()
so C++11 adds std::numeric_limits<>::lowest(), which does
exactly what you'd expect.

What should happen when this code is executed with input variables 0,1,2 and 3?

My question pertains to the following code, it is a classic textbook example:
#include <iostream>
#include <limits>
int main()
{
int min{std::numeric_limits<int>::max()}; ///These two limits
int max{std::numeric_limits<int>::min()};
bool any(false);
int x;
while (std::cin >> x)
{
any=true;
if (x<min)
min = x;
if (x)
max=x;
}
if (any)
std::cout << "min = " << "\nmax = " max << '\n';
}
Also, I was curious to know how to access the documentation that relates to the two limits i refer to in my comment above. Is this something that would be included in the C standard library?
Or would it be found in the documentation for the input / output streams library? In the limits library on cplusplus.com, the devs mention that the min=0, how is the max defined though? as in what are the parameters that define the max value and int could have in any C++ program?
http://en.cppreference.com/w/cpp/types/numeric_limits
http://www.cplusplus.com/reference/limits/numeric_limits/
These two links lead you to documentation about numerical limits in the C++ standard library.
"min()" is not "zero", it's the lowest possible value depending on the type you're using. For an int, the value is the lowest negative number, INT_MIN (probably –2147483648), not zero. For unsigned types, however, it's zero.
For some types, it might mean that all bits are set to 0, giving you the lowest possible value. For other types, it is not that simple.
"max()" is the highest possible value that the type can store. For some datatypes, it simply means that all bits are set to 1, giving you the highest possible value. For other types, it is not that simple, but the result is always the highest possible value that the type can store/represent, nonetheless.
For int, the highest possible value is INT_MAX, which is most likely 2147483647.
Going through your code and explaining exactly what happens, step by step, for the different input values feels out of scope, here, and sounds like I'm doing homework for you. You should try the code and see what happens.

Why is the output not expected to be what it is?

Had been going through this code:
#include<cstdio>
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {1,2,3,4,5,6,7};
int main()
{
signed int d;
printf("Total Elements in the array are => %d\n",TOTAL_ELEMENTS);
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
return 0;
}
Now obviously it does not get into the for loop.
Whats the reason?
The reason is that in C++ you're getting an implicit promotion. Even though d is declared as signed, when you compare it to (TOTAL_ELEMENTS-2) (which is unsigned due to sizeof), d gets promoted to unsigned. C++ has very specific rules which basically state that the unsigned value of d will then be the congruent unsigned value mod numeric_limits<unsigned>::max(). In this case, that comes out to the largest possible unsigned number which is clearly larger than the size of the array on the other side of the comparison.
Note that some compilers like g++ (with -Wall) can be told to warn about such comparisons so you can make sure that the code looks correct at compile time.
The program looks like it should throw a compile error. You're using "array" even before its definition. Switch the first two lines and it should be okay.

C++ maximum non negative int

Is the following going to work as expected on all platforms, sizes of int, etc? Or is there a more accepted way of doing it? (I made the following up.)
#define MAX_NON_NEGATIVE_INT ((int)(((unsigned int)-1) / 2))
I won't insult your intelligence by explaining what it's doing!
Edit: I should have mentioned that I cannot use any standard classes, because I'm running without the C runtime.
There is a standard way to this:
#include <limits>
#include <iostream>
cout << numeric_limits<unsigned int>::max();
Being standard, this is guaranteed to be portable across all platforms.
If you don't want to use defines (and you want a standard way of calculating the limits), then do this:
#include <limits>
std::numeric_limits<int>::min()
These are the ANSI standard defines in limits.h:
#define INT_MIN (-2147483647 - 1) /* minimum (signed) int value */
#define INT_MAX 2147483647 /* maximum (signed) int value */
#define UINT_MAX 0xffffffff /* maximum unsigned int value */
These are the defines from BaseTsd.h:
#define MAXUINT ((UINT)~((UINT)0))
#define MAXINT ((INT)(MAXUINT >> 1))
#define MININT ((INT)~MAXINT)
#include <climits>
INT_MAX
You can have a look at the class numeric_limits, included in the standard library.
See here.
I would modify what you supplied just slightly, since you are coding C++ and not C.
const int MAXINT =(int)(((unsigned int)-1) >> 1), MININT = -MAXINT -1;
I prefer the right shift over the divide by 2, though they do the same thing, because bit shifting is more suggestive of the bit mangling used to generate MAXINT.
MAXINT yields the same thing as you'd get by using
#include <limits>
const int OFFICIALMAXINT = numeric_limits<int>::max();
MININT yields the same thing as you'd get by using
#include <limits>
const int OFFICIALMININT = numeric_limits<int>::min();
Hardcoding these values, as some above suggested, is a baaad idea.
I prefer the bit mangling, because I know it is always correct and I don't have to rely on remembering the library and the syntax of the call, but it does come down to a matter of preference.