In the following code I am inserting at last node. It is working fine. But my doubt is since I have declared Node * last; locally, so whenever a new call is made a new pointer variable will be created and previous one will be removed from the memory after function gets terminated. So how come Node * last; is holding addresses from previous call,since every time it will be freshly created?
first; is pointer to first Node of linked list,it is declared globally.
void insertLast(int x)
{
Node *last;
Node *q=new Node;
q->data=x;
q->next=NULL;
if(first==NULL)
first=last=q;
else
{
last->next=q;
last=q;
}
}
insertLast(2);
insertLast(5);
insertLast(7);
display(first);
output:
2 5 7
Simpler example, same effect:
#include <iostream>
void DONT_DO_THIS(bool init){
int x;
if (init) x = 42;
else std::cout << x << "\n";
}
void foo() {
int y = 0;
}
int main() {
DONT_DO_THIS(true);
DONT_DO_THIS(false);
DONT_DO_THIS(false);
foo();
DONT_DO_THIS(false);
}
Before you read further, try to find out what is the output of this code.
Did you make up your mind?
Do you know what is the output?
Whatever you expect this code to print, it is wrong. The code has undefined behavior and could produce any output. With gcc 11.1 this is the output I get:
42
42
0
Reading from the local variable x
when it is not initialized is undefined behavior. You must not do that! If you do anyhow, one possibility is that next time you call the function the 42
is still stored in a register and x
happens to appear to have that value. In fact x
has no value in that case. It is said to have an indetermiante value that you cannot read.
When turning on optimizations (-O3
) this is the output:
0
0
0
Most likely the compiler realized that the code has UB and optimized away all non-sense code.
No matter what output you get, any output would be in accordance with the C++ standard, because the standard does not mandate what should be the result of compiling code with undefined behavior.
TL;DR: Always initialize variables. Never read from an uninitialized variable. Code with undefined behavior can appear to work, but nevertheless it must be fixed.