开发者

Strange use of strlen

开发者 https://www.devze.com 2023-03-11 00:24 出处:网络
I tried to compile the follow sample code: 开发者_JAVA技巧#include <iostream> #include <stdio.h>

I tried to compile the follow sample code:

开发者_JAVA技巧#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;

int main ()
{
  if (strlen <= 0) {
    cout << "trace1" << endl;
    return 0;
  }
  cout << "trace2" << endl; 
  return 0;
}

The strange thing is that it compiles successfully. Do you have any idea why?

I have not declare the strlen as variable.


Using just the identifier of a function decays to a function pointer of the corresponding type. In this case, strlen is a pointer of the type size_t (*)(const char *). This pointer holds the address of the first instruction of the function in the executable code.

Testing the value of that pointer is legal, whatever the reason may be, although it seems strange in the code fragment you have provided.


strlen without the () gives you a function pointer to the address where the strlen function is allocated in memory.

The program prints "trace1" if the library function strlen is allocated at an address less than 0, which is impossible on every computer in the world, or if it is allocated at address 0 (extremely unlikely but possible). Otherwise, if strlen is allocated at an address that is larger than zero (most likely the case), it prints "trace2".


It's probably decays into an address which decays into an integer. A real compiler will probably fill the screen with warnings.


If you do the same with other functions than strlen, this sample code will print trace2 because strlen is a pointer to function size_t strlen ( const char * str ) and it's value should be a positive number.

cout << (size_t *) strlen << endl;
cout << (size_t *) strcat << endl;

for example the code above prints:

0x7fff84d29110
0x7fff84d63953

on my machine (as you see these are positive numbers because they are started with 7).

Also if I print strlen and strcat without casting to (size_t *) the result will be 1 which means that these functions are valid.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号