As we all know there are no null references.
So I try to compile this line of code
int main{
int &surprise_reference=*(int*)0;
return 0;}
To my surprise this code works without a single warning .
Then I change my code to
int main() {
int&suprise_reference=*(int*)0;
if(&suprise_reference==0)
std::cout<<"you don't know references";
return 0;
}
Output of program is you don’t know references.
Does it mean that dereferencing a null pointer can lead to null references also?
Please help..
What your experiment shows is that it happens to work on your particular computer. That doesn’t mean it’s “ok”.
In particular, this line:
is invalid C++ code, because (exactly as you said) a reference is not allowed to point to a NULL pointer. The result of doing something that’s not allowed by the C++ standard is undefined behavior. In this particular case, on your particular computer, the undefined behavior happens to be pretty benign, but that doesn’t make it predictable, or always OK.
See https://isocpp.org/wiki/faq/references#refs-vs-ptrs for more details. One thing that they point out in particular is that, because the compiler knows that creating a null reference is illegal, it may assume that you haven’t done it — for instance, if you have a function that takes
pas a parameter, and you writeit may conclude from the reference creation that
pis known to be non-NULL, and optimize away the check. Then, if you pass in a NULL pointer forp, things may go badly wrong.(That sort of assumption-and-optimization, by the way, is how a lot of the bad things from undefined code happen.)