c++ - Why is a pointer to NULL-charater not converted to false -


i thought pointer pointed null can converted 0. wrote following program:

#include <iostream> #include <regex> #include <string> #include <cstdlib>  bool is_strtoi(const std::string& str) {     char *p;     std::strtol(str.c_str(), &p, 10);     return *p == '\0'; }  bool is_strtoi1(const std::string& str) {     char *p;     std::strtol(str.c_str(), &p, 10);     return p; //pointer null should converted false; }  int main () {     std::string test1("123asd2");     std::string test2("123123");     std::cout << is_strtoi1(test1) << std::endl;     std::cout << is_strtoi1(test2) << std::endl;     std::cout << "---" << std::endl;     std::cout << is_strtoi(test1) << std::endl; //prints 1     std::cout << is_strtoi(test2) << std::endl; } 

accroding 4.12 section of standard:

a 0 value, null pointer value, or null member pointer value converted false

so why didn't?

you're layer of indirection out! "null pointer" , "a pointer null/zero" 2 different things.

at basic:

  • a null pointer has value zero.
  • it doesn't point other object value zero.

p  == 0;  // yes *p == 0;  // no 

indeed, char* pointing c-string of length 0 (i.e. {'\0'}) not null pointer; valid pointer.

going further, though, notion pointer can "have value zero" implementation detail. in abstract terms, pointers not numbers , shall not consider null pointer have numerical value such zero. evident in introduction of nullptr keyword cannot implicitly converted integer. removing whole discussion "zero", can instead give following improved, more appropriate example:

p  == nullptr; // yes *p == '\0';    // no 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -