0

There seems to be a difference between how c++ increments a global vs local int variable. Can anybody explain why the following code behaves the way it does?

#include<iostream>
using namespace std;

int global = 0;

int main() {
  int local = 0;

  global = (++global) + (++global);
  local =  (++local)  + (++local);

  cout<<global<<endl; // 3
  cout<<local<<endl; // 4

  return 0;
}

Here's my g++ version used if that matters:

gcc version 9.3.0 (Ubuntu 9.3.0-10ubuntu2)

CBH
  • 23
  • 4
  • 2
    Note that this isn't a C++ question per se, but rather one about how your compiler treats two instances of undefined behavior. – Brian61354270 Jul 30 '20 at 14:07
  • 1
    Related, possibly duplicate: [In practice, why would different compilers compute different values of `int x = ++i + ++i;`?](https://stackoverflow.com/questions/62185373/in-practice-why-would-different-compilers-compute-different-values-of-int-x) – Brian61354270 Jul 30 '20 at 14:10
  • https://en.cppreference.com/w/cpp/language/ub – Jesper Juhl Jul 30 '20 at 14:11
  • @SaiSreenivas For *All* the warnings with g++, `-Wall -Wextra -Wpedantic` will get you closer, but that still leaves out a bunch of warnings that have to be enabled individually. – Jesper Juhl Jul 30 '20 at 14:15

0 Answers0