-3

In my machine size of integer data type is 4 bytes so maximum value to the positive side is 2147483647 and to the negative side is -2147483648 in case of a signed int. consider the below c program

#include<stdio.h>

int main(void)
{
    int a = 2147483648;
    int  b = -2147483649;

    printf("%d",a);
    printf("\n%d",b);



    return 0;
}

output: -2147483647 2147483647

why a is implicitly getting converted to -2147483648 and b implicitly getting converted to 2147483647? and why I am getting only for line number 2 the below- given warning

"overflow in implicit constant conversion(-woverflow)"

praveen padala
  • 186
  • 1
  • 1
  • 8
  • 1
    This can be explained by understanding how 2's complement encoding works. https://stackoverflow.com/questions/1049722/what-is-2s-complement – dernst Sep 12 '18 at 01:28
  • overflow and underflow of signed integer are undefined. – Stargateur Sep 12 '18 at 01:28
  • 1. integer overflow is undefined behavior. You should not expect consistent results from these assignments. 2. Your results 1&2 seem intuitive to me (if I were going to define the desired behavior, that's what it would be). I'm not sure about the missing warning, though. That seems *undesirable* :) – zzxyz Sep 12 '18 at 01:29
  • 1
    Possible duplicate of [Why does the negation of the minimum possible integer yield itself?](https://stackoverflow.com/questions/45089640/why-does-the-negation-of-the-minimum-possible-integer-yield-itself) – phuclv Sep 12 '18 at 03:11
  • 1
    @zzyzx There's no UB in this code. You should expect consistent results if rerunning the code on the same implementation. – M.M Sep 12 '18 at 03:20

2 Answers2

1

The warning you want is enabled in GCC by -pedantic. In Code Blocks go over to Settings, Compiler and find "Enable warnings demanded by strict ISO C". Turn that on.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
0

What is happening in your case is integer overflow which causes undefined behaviour.

From C Committee draft (N1570)

3.4.3
1 undefined behaviour
behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements.
2 NOTE: Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).
3 EXAMPLE: An example of undefined behavior is the behavior on integer overflow.

P.W
  • 26,289
  • 6
  • 39
  • 76