View Single Post
  #9 (permalink)  
Old August 7th, 2004, 10:10 AM
davekw7x davekw7x is offline
Authorized User
 
Join Date: Feb 2004
Posts: 76
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Gentlemen (and/or Ladies): the C-language behavior of these expressions is undefined, as Nokomis said. There is no "right answer" for a C program, and, therefore, no "wrong" answer. Different compilers can give different answers, but that does not mean that one is "right" and the other is "wrong".

For example, in case 3, Borland bcc32 version 5.1.1 gives 20, and Gnu gcc 3.3.1 gives 13.

Try the following on your favorite C++ compiler(s). Not using C++? Change cout<< to equivalent printf() and try your favorite C compiler(s).

[code]
#include <iostream>

int main()
{
  int i;
  int k;
  int k2;

  std::cout << std::endl << std::endl;
  i = 2;
  std::cout << " Before calculation, i = " << i << std::endl;
  k = i++ * ++i;
  std::cout << " k = " << k << std::endl << std::endl;
  std::cout << " Before calculation, i = " << i << std::endl;
  k = i++ * ++i;
  i = 2;
  k2= ++i * i++;
  std::cout << " k2= " << k2<< std::endl << std::endl;

  i = 2;
  std::cout << " Before calculation, i = " << i << std::endl;
  std::cout << " i++ * ++i = " << i++ * ++i << std::endl << std::endl;

  i = 2;
  std::cout << " Before calculation, i = " << i << std::endl;
  std::cout << " ++i * i++ = " << ++i * i++ << std::endl << std::endl;

  return 0;
}


Borland gave

Code:
  Before calculation, i = 2
                      k = 9

  Before calculation, i = 4
                      k2= 9

  Before calculation, i = 2
              i++ * ++i = 8

  Before calculation, i = 2
              ++i * i++ = 9

Gnu gave

Code:
  Before calculation, i = 2
                      k = 9

  Before calculation, i = 4
                      k2= 9

  Before calculation, i = 2
              i++ * ++i = 9

  Before calculation, i = 2
              ++i * i++ = 9
Which one is right? Does either one give the answers that you would have guessed?

Since the value of C-language expressions like this is undefined, the "answers" are meaningless.

You could use the outputs to infer something about how each compiler evaluates expressions, but that could change with the next release of the same compiler.

Best regards to all inquisitive minds!

Dave
Reply With Quote