Alex Rivera | Logout

How are local and global variables initialized by default?

Asked 2010-08-24T04:24:11.730
13

Based on below, am i right?

  • global_A reference is initialized to null.
  • global_int is 0
  • local_A reference is null
  • local_int is uninitialized
  • Both global_A.x and local_A.x is uninitialized.

THanks for any help.


A global_A;
int global_int;

class A {
  public : int x;
}

int main()
{
  int local_int;
  A local_A;
}
Edit
Report

3 Answers

7

There are no references in your code, so any of your points that mention "references" make no sense.

In your example, both global object - global_int and global_A - are zero-initialized. Both local objects - local_int and local_A - contain indeterminate values, which means that local_int and local_A.x are not initialized.

P.S. Of course, as other already noted, your code is non-compilable. You can't declare A objects before declaring class A (and you are missing a ; after the class definition).

answered 2010-08-24T04:35:22.130
-2

This code won't compile unless you forward declare A.

global_A reference is initialized to null - No, it will reference an A object. global_int is 0 - Think so, need to check. local_A reference is null - No, same as with global_A. local_int is uninitialized - Yes, it will get some garbage value. Both global_A.x and local_A.x is uninitialized - Yes.

You can always debug and see for yourself.

answered 2010-08-24T04:35:11.553
-2

well guys .. i am more confused as i see responses from here. Anyway i did a test as shown below:

1 #include

  2 using namespace std;
  3 
  4 class A {
  5 
  6 public :
  7         A() : x(9) {};
  8         int x;
  9 
 10 };
 11 
 12 A global_a;
 13 int global_b;
 14 
 15 int main() {
 16 
 17         A local_a;
 18         int local_b;
 19         cout << "global_a.x = " << global_a.x << '\n';
 20         cout << "local_a.x = " << local_a.x << '\n';
 21 
 22         cout << "global_b = " << global_b << '\n';
 23         cout << "local_b = " << local_b << '\n';
 24 
 25 }

Results using my g++ compiler on ubuntu linux:

global_a.x = 9

local_a.x = 9

global_b = 0

local_b = 0

I do think local_b should be undefined but somehow compiler initialized it by default. However local_a .. i am not sure if that should be initialized by default. From the testing here .. local_a seem to be initialized. Not sure if that complies with standard c++ specification (eg C++ PRimer 4th edition says default constructor is used regardless where a class variable is declared - does that means variable of class type is initialized whether it is global or local?).

Whatever it is .. it is one big hell of confusion. Maybe i should quit learning C++. Java is so much more straight forward. Hell yeahhh!!

answered 2010-08-25T03:19:29.083

Your Answer