Despite the seemingly intuitive expectation of an error, invoking methods through null pointers in C may appear to execute. This behavior raises questions regarding the standard compliance and optimization practices used by compilers.
To delve into this matter, consider the following example:
<code class="cpp">#include <iostream> using namespace std; class test { int i; public: test():i(0){ cout << "ctor called" << endl;} void show() { cout << "show fun called" << endl; } }; int main(int argc , char *argv[]) { test *ptr = NULL; ptr->show(); return 0; }</code>
In this snippet, a class test is defined with a constructor and show() method. In the main() function, a pointer ptr is initialized to NULL and then the show() method is invoked through ptr.
Surprisingly, the program executes without errors and prints "show fun called" without triggering the constructor. This is due to the fact that in C , the compiler knows the type of the null pointer, enabling it to identify the method's code. Since the show() method does not utilize the this pointer, it runs successfully.
However, this behavior is considered undefined in the C standard. Compilers are permitted to optimize code by not checking if a pointer is NULL before calling a method. While this optimization improves efficiency, it compromises safety and predictability.
The above is the detailed content of Why Does Invoking a Method Through a Null Pointer in C Sometimes Work?. For more information, please follow other related articles on the PHP Chinese website!