Search code examples
clibuv

Unfamiliar C syntax?


I am trying to understand C code written by others and have come across a piece of code that I do not understand all of the syntax and the parts I don't understand I don't know how to search for. I would appreciate either an explanation or information on how to search this and other similar things I may encounter, or both. The code in question is the following line:

int r = uv_listen((uv_stream_t*) &server, 128, on_new_connection);

I understand that r is a variable that is being declared and initialized to the value returned by the function "uv_listen()", 128 is a literal int paramater, on_new_connection has to be a function pointer since that is the name of a call back function that is called. server is a variable of a custom type (uv_tcp_t) and with the & it is referring to the address of server. What I don't understand is the "(uv_stream_t*) &server". It looks like this is one of the parameters to the function. I could understand a function call that returned a value as a parameter but this doesn't look like a function call. "uv_stream_t" is another custom type that is defined in their code.

I don't know if it is helpful in understanding what it means but the line of code is from sample code written to help in understanding how to use libuv.


Solution

  • It's just a type cast. &server gives the address of the server variable and (uv_stream_t*) casts the type of that address.

    Based on the other information in your post, it seems that server is of type uv_tcp_t, but uv_listen wants a pointer to uv_stream_t. That's why you take the address of server and cast it to uv_stream_t*.

    Note: this only makes sense because of how libuv defines uv_tcp_t and uv_server_t — in general you can't just cast pointer types to other pointer types and expect anything reasonable to happen.