What's the meaning of 'int foo(int);'?

Jun 9, 2021 at 11:57am
This question may sound strange. I'd found four kinds of initialization(value, default, direct, list) and tried many variable definitions which look similar. Below is one of my tries among them.

1
2
3
4
5
6
7
#include <iostream>

int main()
{
  int foo(int);
  std::cout << foo << std::endl;
}


Now I know 'int foo(int);' is not a definition of variable. It is a function declaration. But when I compiled it and run, terminal showed me the digit 1 without any diagnostic message. I didn't understand it because foo isn't defined anywhere. How is this output shown? Did I just invoke undefined behavior?
Last edited on Jun 9, 2021 at 11:58am
Jun 9, 2021 at 12:02pm
Well, when I run it using VS2019 I get an expected linker error regarding unresolved symbol foo.
Jun 9, 2021 at 12:06pm
the site compiler evaluates foo as 'true' with a warning. This seems like a minor bug.
if you call foo instead of printing its address, it is not happy.
Last edited on Jun 9, 2021 at 12:07pm
Jun 9, 2021 at 12:28pm
Thank you seeplus and jonnin, I had to say I used g++ compiler.
I tried this code with VS2019 and the site compiler. I learned that the function pointer value is implicitly converted to bool value 'true' and VS2019 doesn't allow this code.
Last edited on Jun 9, 2021 at 12:32pm
Jun 9, 2021 at 2:20pm
Clang's warning is:
1
2
3
4
5
6
7
8
9
10
11
kbw@squizey:/tmp % vim x.cc; sh -c 'CXXFGLAGS="-std=c++17 -g -Wall -Wextra" make x && ./x'
c++ -O2 -pipe  x.cc  -o x
x.cc:6:16: warning: address of function 'foo' will always evaluate to 'true' [-Wpointer-bool-conversion]
  std::cout << foo << std::endl;
            ~~ ^~~
x.cc:6:16: note: prefix with the address-of operator to silence this warning
  std::cout << foo << std::endl;
               ^
               &
1 warning generated.
1


g++
1
2
3
4
5
6
7
kbw@teppi:~/tmp2$ vim x.cc && CXXFLAGS="-std=c++17 -g -Wall -Wextra" make -B x && ./x
g++ -std=c++17 -g -Wall -Wextra    x.cc   -o x
x.cc: In function ‘int main()’:
x.cc:6:16: warning: the address of ‘int foo(int)’ will never be NULL [-Waddress]
    6 |   std::cout << foo << std::endl;
      |                ^~~
1


My expected behaviour is what VS is doing.
Last edited on Jun 9, 2021 at 2:22pm
Jun 9, 2021 at 2:20pm
If you want to print the function address you need to cast it to void*.
This will definitely not work if the function is not defined.
Topic archived. No new replies allowed.