SSDong
SSDong

Reputation: 145

weird C++ pointer declaration

I am writing a really small program about Depth First Search algorithm. At the end of program, a delete of the memory is required.

for(int i = 0; i < V; i++) {
    Vertex* temp1, *temp2 = graph->adjacentList[i];
    while(temp1 != NULL) {
        temp2 = temp1->next;
        delete temp1;
        temp1 = temp2;
    }
}

This code deletes the adjacent lists of the graph. The code can compile and run but with runtime error. The error message is

The variable 'temp1' is being used without being initialized.

Please look another piece of code:

for(int i = 0; i < V; i++) {
    Vertex* temp1 = graph->adjacentList[i];
    Vertex* temp2 = graph->adjacentList[i];
    while(temp1 != NULL) {
        temp2 = temp1->next;
        delete temp1;
        temp1 = temp2;
    }
}

This code can compile and run and without any error message ! The only difference is the declaration. This is weird, at least for me.

Anyone can come up with an idea?

Upvotes: 2

Views: 136

Answers (2)

Yu Hao
Yu Hao

Reputation: 122383

Vertex* temp1, *temp2 = graph->adjacentList[i];

is equivalent to

Vertex *temp1;
Vertex *temp2 = graph->adjacentList[i];

You can see why there's an error says temp1 is not initialized.

Upvotes: 10

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

In this code segment:

Vertex* temp1, *temp2 = graph->adjacentList[i];

You are not actually initializing temp1.

Consider the following:

int a, b = 2;

What is a? it is not 2, it is un-initialized. Your second implementation is more correct.

Upvotes: 5

Related Questions