markzzz
markzzz

Reputation: 47945

Which kind of explicit conversion is done here?

This is the code that compile and works in my MVS2015:

#define STRING_TEST "Test String"

using namespace std;

void test(char * str) {
    cout << str;
}

int main ()
{
    test(STRING_TEST);
}

I guess that STRING_TEST was converted into a char[11]. Instead, since I pass it without &, it creates a char * pointer? Or what am I missing?

Upvotes: 0

Views: 66

Answers (2)

Rakete1111
Rakete1111

Reputation: 48938

"Test string" is of type const char[12], not char[11] (you forgot '\0').

Your code is equivalent to

test("Test String");

Macros just do a find+replace, so it's not "converted".

Arrays decay into pointers, to here, the char arrays decays into char*. And so test calls it. This however is has been removed as of C++, since const char* != char*.

Upvotes: 2

Peter
Peter

Reputation: 36597

There is no explicit conversion at all in your code.

STRING_TEST is a macro, so the statement

test(STRING_TEST);

is preprocessed into

test("Test String");

which will then be compiled.

"Test String" is a string literal, so when passed to a function will be IMPLICITLY converted to a const char *.

So, assuming your compiler complies with the standard, the statement will not compile (since implicit conversion from const char * (or from a string literal to char *) is not permitted.

However, some compilers do allow this implicit conversion (for reasons of backward compatibility to older versions of C). Those compilers can often be made to complain by cranking up diagnostics (e.g. with Microsoft compilers adding the /Wall command line option).

Upvotes: 2

Related Questions