dexterous
dexterous

Reputation: 6536

What is the difference between these two C function calls?

I am calling the following library function in two ways:

unsigned int
LsSendToQ(unsigned int p4Node, const char queueName[4], lsMsg *pMsg,
          unsigned int prio) {

}

The first way :

LsSendToQ((unsigned int)0, (const char *)Q_NAME, (lsMsg *)(void *)pMsg, 0) 

and the second way :

LsSendToQ((unsigned int)0, (const char *)Q_NAME, (lsMsg *)pMsg, 0) 

Both calls compile fine, but which one is the right way ? And why is (void *) used in the first call, which looks like a function pointer to me ?

Upvotes: 4

Views: 198

Answers (3)

Shafi
Shafi

Reputation: 1970

A pointer to void is a "generic" pointer type. A void * can be converted to any other pointer type without an explicit cast. You cannot dereference a void * or do pointer arithmetic with it; you must convert it to a pointer to an complete data type first. See this answer.

So the parameter pMsgis not directly compitable to lsMsg * then the 2nd calling is a possible way to use this in the function calling[ I didn't tested it].

By the way, as long as type of pMsg is lsMsg * the 1st one is enough.

Edit:

The 2nd one is enough as it covers the 1st one.

Upvotes: 3

Lundin
Lundin

Reputation: 215350

The second version is the correct one.

The first call looks like an attempt to dodge incompatible type warnings. If pMsg is not compatible with lsMsg * you could kill the compiler warning by casting to void* in between.

You shouldn't do this though, because it almost certainly hides a bug in your program! Either the two pointer types are completely incompatible, in which case the program may instantly crash & burn upon accessing the pointer. Or they are in theory compatible, but the compiler implements type aliasing and the (void*) cast would then hide a violation of the "strict aliasing rule". In either case you have undefined behavior and a severe bug.

Upvotes: 3

Sam Liao
Sam Liao

Reputation: 46173

I see no reason for the first way of converting the pointer type twice. Just use the second way is enough.

Upvotes: 2

Related Questions