Pass NULL value as function parameter in C++

In this tutorial, we are going to discuss the topic “How to pass NULL value as a function parameter in C++“.

So before starting this topic, let’s first recall “What is NULL?“.

  • “NULL” in C++ by default has the value zero (0) OR we can say that, “NULL” is a macro that yields to a zero pointer i.e. no address for that variable.
  • So if you look closely at the definition then you will notice one thing that, “NULL” is both, value as well as a pointer.
  • You can consider “NULL” as value when you are directly assigning it to a variable at the time of defining a variable.

For example like,

#include <iostream>

int main(void) 
{
   int  var = NULL;
   std::cout << "The value of var is " << var ;
 
   return 0;
}

This will give you the output,

The value of var is 0
  • This will not generate any error, but will give you a warning message saying,

warning: converting to non-pointer type ‘int’ from NULL [-Wconversion-null]

 

Pass NULL as a parameter

  • Similar is the case when you pass “NULL” as a parameter. It will not generate any error but pops up a warning message.
  • Below code snippet will help you to understand more clearly,
#include <bits/stdc++.h>
using namespace std;

void nULL_fun(int a)
{
  cout<<"Value of a: "<<a;
}

int main()
{
 nULL_fun(NULL);

 return 0;
}
  • This will give you a warning message saying,

warning: passing NULL to non-pointer argument 1 of ‘void nULL_fun(int)’

  • But you will get the output as,
Value of a: 0
  • But while working on big projects you should not avoid such warnings. So to fix this warning you should take the formal argument of pointer type.
  • So to remove such warning message the above program can be written as,
#include <bits/stdc++.h>
using namespace std;

void nULL_fun(int *a)
{
  cout<<"Value of a: "<<a;
}

int main()
{
 nULL_fun(NULL);

 return 0;
}
  • The output will be,(without warning message)
Value of a: 0
  • This ‘0’ is the address of “NULL” which is zero. Similarly in the 1st program, you can replace variable “int var” with “int *var” so as to remove the warning message.

(Note: Ambiguity will be created if there are two functions with the same name and arguments of type say “int” and ” int *” respectively. This is discussed in my tutorial “Difference between NULL and nullptr”.)

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *