-5

Watch at the following simple code,
Compiling it with the command g++ -std=c++14 -g -O2 CODE.cpp
produces the strange Output :

Why this ?? -2147483648

# include<bits/stdc++.h>

using namespace std;

# define pc(x)    putchar(x)

template <class T>
inline void pd(T num, char ch = ' '){

   num = -num;
   cout << "Why this ?? " << num << endl;

}

int main(void){

   pd(INT_MIN);

   return 0;
}

Please explain this behavior !!

Prem KTiw
  • 535
  • 1
  • 4
  • 17

1 Answers1

2

Type deduced for INT_MIN is int.
-INT_MIN may cause integer overflow (if INT_MIN = -INT_MAX - 1 which is true on most platforms) and thus it causes undefined behaviour.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100