c++ - Why does the root pointer get initialized to null always? -


i'm confused following code:

class tree { protected:     struct node {         node* leftsibling;         node* rightsibling;         int value;     };   private:     node* root;     int value; ..... public:     void addelement(int number) {         if (root == null) {             printf("this value of pointer %lld\n",(long long)root);             printf("this value of int %d\n",value);             ...             return;         }         printf("not null\n");     } };   int main() {     tree curtree;     srand(time(0));     for(int = 0;i < 40; ++i) {         curtree.addelement(rand() % 1000);     } } 

the curtree variable local main function expected not have members initialized 0, both initialized.

no, has unspecified contents. contents might random memory garbage, or happen 0, depending on whatever data left in memory location beforehand.

it might happen due way code compiled, particular stack location containing root has 0 (say, because earlier local variable occupying same stack location ended 0). cannot rely on behavior -- must initialize before reading back, otherwise enter land of undefined behavior.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -