tags:

views:

175

answers:

2

Please have a look at the below mentioned code snippet and tell me the difference?

int main()
{
struct sockaddr_in serv_addr, cli_addr;
/* Initialize socket structure */
    bzero((char *) &serv_addr, sizeof(serv_addr));
}

Now, what if i do something similar without typecasting (char *), then also i feel it will do the same thing? Can someone clarify?

/* Initialize socket structure */
bzero( &serv_addr, sizeof(serv_addr));
+4  A: 

Since the first parameter is void *, you only need to cast in C++.

In C this is not necessary, as a void * was introduced1 precisely so that you wouldn't need to cast it to or from other object2 pointers. (Similarly with malloc() and other functions that deal with void *s)


  1. In C89.
  2. Any non-function pointer.
Alex
Emmm... why do I need to cast from `SomeType*` to `void*` in C++? Perhaps you meant that the reverse cast is required in C++, but not in C?
sharptooth
I mean that a conversion from `void *` to any other non-function pointer is implicit in C, and does not require a cast. In C++ this is no longer true.
Alex
Okay, where is `void*` converted to anything in this question? I only see a `SomeType*` to `void*` conversion.
sharptooth
The conversion happens during the call to bzero, as the first parameter is `void *`, but the passed argument is `struct sockaddr_in *`. Actually, it looks like his prototype may take a `char *` instead. Perhaps he has an old header file.
Alex
@sharptooth: in C++ the type checking is stricter. And probably necessary since bzero could conceivably be overloaded so that bzero((void*)x, size) could call a different function to bzero((char*)x, size)
JeremyP
@Alex and JeremyP: what sharptooth is saying is that C++ is fine with an implicit cast *to* `void*` (just like C), which is what's happening in the code snippet. Where C++ differs from C (in this area) is that it doesn't allow an implicit cast *from* `void*` - but that's not happening in the example.
Michael Burr
+2  A: 

The cast is not needed, since bzero() accepts void* as the first argument and AnyType* can be implicitly converted to void*.

sharptooth