You are here:

C++/while loop

Advertisement


Question
Sir I have a simple programee

#include <stdio.h>
main(){
  int i,j ;
  i = 1;

  while (i > 0) {
      j = i;
      i++;
  }
  printf ("the maximum value of integer is %d
",j);
  printf ("the value of integer after overflow is %d
",i);
}

in this programe how doe's it works specially i++ how its works kindly let me know step by step

Thank you for your reply in this regard

Answer
The int type specifies a _signed_ integer value of the (bit) size that is natural for the processor (although some 64-bit compilers keep an int at 32-bits in size).

On a majority of generally available computers today of the desktop/workstation/server variety signed integers are represented using 2s complement format. An alternative would be sign magnitude format. See for example:

   http://en.wikipedia.org/wiki/Signed_number_representations
   http://en.wikipedia.org/wiki/Two%27s_complement   

In either case if the top most bit is 1 it represents a negative value.

I shall assume 2s complement format is used for signed integer values.

In the loop in your question's code the int named i starts with a value of 1. Being greater than zero the loop body is executed.

The value of i, i.e.. 1, is saved in the int named j.

The value of i is incremented by 1 to 2, 2 is greater than 0 still so the loop continues. Notice that j is _still_ 1 at this point. That is if the loop terminates the value of j will be the previous value of i.

The loop continues in this fashion, incrementing i and setting j to the previous value until all bits of i bar the top bit are set. For a 32-bit int value this will be the binary value:

   0111 1111  1111 1111  1111 1111  1111 1111

Or the hexadecimal value:

   7FFFFFFF

Which is the value 2^31 - 1 (one less than 2 to the power 31), i.e.2147483647 decimal.

Adding 1 to this value (i.e. incrementing it) gives the value (in binary):

   1000 0000  0000 0000  0000 0000  0000 0000

Which has the top bit set, so represents a _negative value_ - remember i is a _signed_ integer value. We are assuming 2's complement so this will represent the value -2147483648, which is _not_ greater than zero so the loop terminates, with

   i = 1000 0000  0000 0000  0000 0000  0000 0000 binary = -2147483648 decimal

And j has the previous value:

   j = 0111 1111  1111 1111  1111 1111  1111 1111 binary =  2147483647 decimal

Hence the loop terminates at the cross over point between positive and negative values.

Strictly speaking the loop relies on undefined behaviour. The ISO/ANSI C++ (1998) standard contains the clause (5/5):

       "If during the evaluation of an expression, the result is not mathematically defined
        or not in the range of representable values for its type, the behaviour is undefined,
        unless such an expression is a constant expression (5.19), in which case the program
        is illformed. [Note: most existing implementations of C++ ignore integer overflows.
        Treatment of division by zero, forming a remainder using a zero divisor, and all
        floating point exceptions vary among machines, and is usually adjustable by a library
        function. ]"

(and I suspect the equivalent C standard document would contain something similar - but you are asking a C++ expert in the C++ question category!!)

Note the sections "or not in the range of representable values for its type" and "the behaviour is undefined, unless such an expression is a constant expression in which case the program is illformed". Adding 1 to the maximum value that can be held by and int will of course produce such an out of range value - however as noted "most existing implementations of C++ ignore integer overflows" and the effect is generally to wrap around - in this case from the MAX_INT value to the MIN_INT value - think of the range of signed numbers as a ring running one way from 0 to INT_MAX and the other from 0 to INT_MIN, the ends of the range are 'joined' at INT_MIN and INT_MAX, as very poorly shown below (view using a fixed spaced font such a Courier):

           9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9
           10                                          -10
           .                                             .
           .                                             .
           .                                             .
           INT_MAX-2                             INT_MIN+3
            INT_MAX-1 INT_MAX INT_MIN INT_MIN+1 INT_MIN+2

You might like to consider what happens if you make i and j unsigned ints instead.

Hope this helps a bit.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2012 About.com, a part of The New York Times Company. All rights reserved.