Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use `operator const char*` in printf

Tags:

c++

struct MyClass
{
    operator const char* ()
    {
        return "hello";
    }
};

int main()
{
    MyClass obj;  
    std::cout << obj;    // ok
    printf("%s\n", obj); // Crash
}

Why does object with operator const char* can not be automatically converted to const char* string in printf for mapping the %s?

Is it just because there is no type awareness in printf-like functions and %s only expect a array of char with terminal 0?

like image 354
Chen OT Avatar asked Aug 14 '26 20:08

Chen OT


2 Answers

Why? Because of the limitations on variadic parameters in C++: they have essentially no type, you can think of them as void * (but they're not).

So knowing that, the compiler has no idea you think that should be a string. It could very well need to be an integer, or a double, or another object. Or just itself, which the compiler chooses.

like image 85
Blindy Avatar answered Aug 16 '26 09:08

Blindy


When you call printf with:

printf("%s\n", obj);

the compiler does not use the auto conversion function to convert obj to char const*. obj is passed to printf by value and printf tries to treat that value as though it is char const*. As a consequence, your program exhibits undefined behavior. You'll have to explicitly cast obj to char const* to make your program behave predictably.

printf("%s\n", (char const*)obj);

If you turn on warning levels in your compiler, you'll probably see something to indicate that using obj in that printf call is not right. With g++ -Wall, I get:

socc.cc:16:23: warning: format ‘%s’ expects argument of type ‘char*’, but argument 2 has type ‘MyClass’ [-Wformat=]
     printf("%s\n", obj); // Crash
like image 40
R Sahu Avatar answered Aug 16 '26 10:08

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!