0

So, I just started with C++ and was doing random things with a snippet of code I found on the net. The code is a simple use of defining namespace. After my changes in the code, it looked like,

#include <iostream> 

using namespace std; 
namespace ns1 { int value() {return 5;}} 
namespace ns2 { int value() {return -5;}} 

int main() { 

cout << ns1::value<< '\n';  //5 will be displayed

cout << ns2::value<< '\n';     // -5 will be displayed

}

Now, i know that i have called the wrong function and it should be ns1::value() instead of ns1::value , but my question is why is the code still working? And why is it giving an output of 1?

  • 1
    `cout` doesn't work with function pointers. The only overload that is compatible is the one that prints a `bool`. So it will print `1` for any non-null function pointer. – François Andrieux Mar 07 '22 at 20:03
  • gcc compiler warning will actually tell you what is about to transpire. "address of function... will always evaluate to true [-Wpointer-bool-conversion]" – WhozCraig Mar 07 '22 at 20:05
  • @FrançoisAndrieux but this code should not work at all as i am calling an undefined function – Aseem Mittal Mar 07 '22 at 20:05
  • 2
    What 'undefined function' are you calling? – WhozCraig Mar 07 '22 at 20:06
  • 1
    @AseemMittal Every function in your example is defined. Which function to you think is undefined and called in your code? – François Andrieux Mar 07 '22 at 20:06
  • `cout << std::boolalpha;` at the beginning of your program will reveal more. – Drew Dormann Mar 07 '22 at 20:07
  • You are printing the address or location of the function. You'll probably want `ns1::value()` and `ns2::value()` note the use of `()` to call the function. – Thomas Matthews Mar 07 '22 at 20:09
  • @WhozCraig when defining the function "ns1::value()", i had used a different syntax than the one when i called for that function, so i think it is an undefined function being called – Aseem Mittal Mar 07 '22 at 20:13
  • @AseemMittal `ns1::value()` and `ns1::value` are using the same function. The name of the function is `ns1::value`, but with `()` you _call_ the function. If you use the name without `()` you are not calling the function. Instead you are taking the address of the function. But it is not a different function. – user17732522 Mar 07 '22 at 20:52

0 Answers0