Swan
Swan

Reputation: 43

void * assignement from C to CPP

I'm wondering why this code works in C and not in C++

void* dum;
dum = "dum";

I have the C++ error

In function 'int main()':
8:10: error: invalid conversion from 'const void*' to 'void*' [-fpermissive]

Any C++ equivalent?

Upvotes: 0

Views: 188

Answers (3)

vmp
vmp

Reputation: 2420

You would have to cast it back to get the result you want.

String literals have type const char* so your pointer would need to be constalso. You cannot assign something that is const to a pointer to non const.

const void* dum = "dum";
cout << static_cast<const char*>(dum);

Try this coutwithout the cast to see what you get. It would be interpreted as a void pointer...

Upvotes: 0

0___________
0___________

Reputation: 67476

    void* dum;
    dum = (void *)"dum";
    const void* dum = "dum";
    const char* dum = "dum";
    const char* dum;
    dum = "dum";
    const void* dum;
    dum = "dum";

Upvotes: 1

eerorika
eerorika

Reputation: 238311

I'm wondering why this code works in C and not in C++

It doesn't work in C++ because string literal is an array of const char.

Any C++ equivalent?

const char* dum = "dum";

Upvotes: 5

Related Questions