-3

I'm new to C++ but I'm facing comparing Problem

void print(int x, char const*b=""){
    std::cout << x;
    if(b == "a"){
    /*this code not execute I don't know why ?*/
      std::cout << "\n";
    }
}

/*calling my print function*/
print(2020, "a")

1 Answers1

2

Your check is validating the pointer's address The empty string has an address in memory, so the check doesn't return true, thus the if true branch is not executed.

Is you are using C++ you might consider changing the argument to use type std::string and check using std::string::empty.

Spidey
  • 2,508
  • 2
  • 28
  • 38
  • the above code also not working why ???? – Ḉớᶑẽr Ħậꞣǐɱ Sep 27 '20 at 16:03
  • 1
    Because you are comparing pointers and not what they point to. if you are permitted remove the `char*` and use the proper `c++` string which is std::string. With a std::string the comparison would work just by changing `void print(int x, char const*b=""){` to `void print(int x, std::string b){` and adding `#include ` – drescherjm Sep 27 '20 at 16:19