Thread: How pass NULL for a parameter in a function?

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    184

    How pass NULL for a parameter in a function?

    While the below compiles (g++ compiler) it throws a runtime error "terminated in an unusual way." How can I allow passing NULL?

    Code:
    void doSmth(std::string str)
    {
          //This causes the error only if NULL was actually passed
         if ( &str == NULL ) printf( "null" );
    }
    
    int main(...)
    {
         //This one works fine
         doSmth( "string" );
    
         //This cause it to crash
         doSmth( NULL );
    
         //This will also cause a crash
         std::string tmp(NULL);
         doSmth( tmp );
    }

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Do you just want to pass an empty string? Use string() or "" to do that.

    If you want something that is different than an empty string (because an empty string means something else) then you want to overload doSmth or have it take a pointer parameter that can be null.

  3. #3
    Registered User
    Join Date
    Nov 2006
    Posts
    184
    Cool.

    BTW, thank you to all of you guys who have been VERY helpful to someone learning c++. I really appreciate it!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Invalid conversion from 'void*' to 'BYTE' help
    By bikr692002 in forum C++ Programming
    Replies: 9
    Last Post: 02-22-2006, 11:27 AM
  2. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  3. Help with yacc/compiler design/seg fault
    By trippeer in forum C Programming
    Replies: 1
    Last Post: 04-08-2005, 03:43 AM
  4. Replies: 6
    Last Post: 03-02-2005, 02:45 AM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM