-1

The following code never prints out the counter, assuming the compiler does something intelligent to initialize int data member types to zeros?

include <iostream>

using namespace std;

class A {
  public:
    int a;
    int b;

    A(): b(a), a(b) { }
};

int main()
{
    A* p = new A;
    int counter = 0;

    while (!(p->a)) {
        p = new A;
        counter++;
    }

    cout << counter << endl;
}
user1147800
  • 237
  • 4
  • 14
  • This is undefined behavior. You are using uninitialized variables to initialize other variables. I would just say you got lucky getting them as zero. – Some programmer dude Jun 25 '12 at 09:25

2 Answers2

3

The following code never prints out the counter, assuming the compiler does something intelligent to initialize int data member types to zeros?

The assumption is wrong. The value of an uninitialized variable is indeterminate. It could be some random number that just happens to be there in memory.

Change the constructor line to this:

A(): b(0), a(0) { } 

This explicitly initializes the values to zero, and also communicates intent clearly. Remember that code is there for humans to read. The computer never actually sees your C++ code.

Also note that the following is equivalent:

A(): b(), a() { } 

although I don't personally use this method of initialization.


The initialization is not the only problem with the code. For one, you have huge memory leaks in the code, as you don't delete the instances of A you newed. Go pick up a good introductory C++ book and learn proper modern C++, as your post demonstrates that you don't quite have a grasp of the language fundamentals.

Community
  • 1
  • 1
In silico
  • 51,091
  • 10
  • 150
  • 143
  • *pedantic* - the `0` inside the parenthesis is redundant. – Luchian Grigore Jun 25 '12 at 09:26
  • Also, it's not the values that are necessarily undefined, but the whole behavior of the program. – Luchian Grigore Jun 25 '12 at 09:27
  • @LuchianGrigore: Since delving in to pedantism: The value of an uninitialized variable is *Indeterminate* and *not Undefined*. – Alok Save Jun 25 '12 at 09:30
  • 5
    @Luchian Grigore: "also communicates intent clearly". While experienced C++ programmmers such as ourselves understand what `a(), b()` means in a `ctor-initializer`, it's just better code readability to have `a(0), b(0)` IMO. – In silico Jun 25 '12 at 09:30
1

This is undefined behavior. a is the first to get initialized, and it's initialized to b, which is an uninitialized variable. If you want value-initialization (or to 0):

A(): b(), a() { }

Note that the order of initialization is the order in which the members appear in the class definition, not in the member initialization list.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625