YouTip LogoYouTip

Cpp Null Pointers

# C++ Null Pointers [![Image 3: C++ Pointers](#) C++ Pointers](#) When declaring a variable, if there is no definite address to assign, it is a good programming practice to assign a NULL value to the pointer variable. A pointer assigned a NULL value is called a **null** pointer. A NULL pointer is a constant defined in the standard library with a value of zero. Consider the following program: ## Example #include using namespace std; int main () { int*ptr =NULL; cout<<"ptr the value is "<< ptr ; return 0; } When the above code is compiled and executed, it produces the following result: ptr the value is 0 On most operating systems, programs are not allowed to access memory at address 0 because that memory is reserved by the operating system. However, memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains a null (zero) value, it is assumed to point to nothing. To check for a null pointer, you can use an if statement, as shown below: if(ptr) /* If ptr is not null, then proceed */if(!ptr) /* If ptr is null, then proceed */ Therefore, if all unused pointers are given a null value and you avoid using null pointers, you can prevent the misuse of an uninitialized pointer. Many times, uninitialized variables hold some garbage values, making the program difficult to debug. [![Image 4: C++ Pointers](#) C++ Pointers](#)
← C Function MbtowcC Function Mblen β†’