-3

what will happen when the integer crosses its limit? The output is 3595 , and how it will come? And it is 2 byte type ?

#include<stdio.h>
#include<conio.h>
void main()
{
  int n=12,res=1;
  clrscr();
  while(n>3)
  {
    n+=3;
    res*=3;
  }
  printf("%d",n*res);
  getch();
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Related: https://stackoverflow.com/questions/3948479/integer-overflow-and-undefined-behavior – Barmar Dec 29 '17 at 07:02
  • 1
    In order to answer this question yourself (which you will have to do, because of undefined behaviour, which prevents a generic answer), you should generously add calls to printf(). Also print `sizeof(int)` in order to find the answer to your second question in your environment. – Yunnosch Dec 29 '17 at 07:14

2 Answers2

3

The program will have undefined behavior.

The condition you gave is non terminating. It's a loop where the condition will never be terminated in a well defined manner.

You will go on multiplying and then once it will overflow. And then if you get a negative result in n or <=3 then it will stop. And in the mean time res has also overflown. As a result you will not be sure how this program behaves. We can't be sure of what the result will be.

user2736738
  • 30,591
  • 5
  • 42
  • 56
  • Yeah i understood, but if we run this program in compiler , certainly will get a answer, what will happened when it is run? –  Dec 29 '17 at 07:09
  • @Mathan.: Yep..that's what is being explained. You can never be sure. Mostly it will overflow after certain point and then the result will be something definite but again it depends on the architecture - how it handles overflow stuff like that. You can never be sure. Maybe your professors machine would behave differently than yours when you check the answer. :) – user2736738 Dec 29 '17 at 07:12
1

The behaviour is undefined - you should not rely on anything specific. Common manifestations on int overflow are:

  1. Wraparound such that 1 + INT_MAX becomes INT_MIN. This is what every Windows PC I have encountered does. The bit pattern produced by the operation matches the unsigned cousin exactly.

  2. Clamping such that 1 + INT_MAX becomes INT_MAX. I last observed this on a machine (with signed magnitude int) running a variant of UNIX in the 1990s.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483