Skip to content

static_cast instead of reinterpret_cast for interpreting pointer to integral conversion #512

@napierson

Description

@napierson

See for example https://cppinsights.io/lnk?code=bG9uZyBsb25nIGludCBjaGFyUHRyVG9JbnQoY29uc3QgY2hhciogc3RyKQp7CiAgICBsb25nIGxvbmcgaW50IGEgPSAobG9uZyBsb25nIGludClzdHI7CiAgICByZXR1cm4gYTsKfQoKaW50IG1haW4oKSB7CiAgICBjb25zdCBjaGFyKiBzdHIgPSAiMTIzIjsKICAgIGNoYXJQdHJUb0ludChzdHIpOwp9&insightsOptions=cpp17&std=cpp17&rev=1.0

Source:

long long int charPtrToInt(const char* str)
{
    long long int a = (long long int)str;
    return a;
}

int main() {
    const char* str = "123";
    charPtrToInt(str);
}

Output:

long long charPtrToInt(const char * str)
{
  long long a = static_cast<long long>(str);
  return a;
}


int main()
{
  const char * str = "123";
  charPtrToInt(str);
  return 0;
}

But the conversion from const char* to long long is being accomplished by a reinterpret_cast<long long>, not a static_cast<long long>. If you try to substitute in the static_cast, the code fails to compile.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions