Say I have a windows socket named socket
. If socket
was passed to a function which doesn't write to it. For instance say a function that sends a simple message/bytes to the client like Hello you're connected to the server!
.
For example:
void send_hello(SOCKET socket, char* data) {
send(socket, data, sizeof(data), 0);
}
Would it be safe to pass the socket as const
? For example:
void send_hello(const SOCKET socket, char* data) {
send(socket, data, sizeof(data), 0);
}
Something in my brain tells me I should be passing socket
as const
rather than passing it as writeable memory. I know sockets are file descriptors, so I'm obviously confused as to how they work and if they're always or ever written to. However my code works when passing socket
as const
.
My overall question is:
Is it ok to pass a variable with the type SOCKET
object as const
? Or should said SOCKET
always be in writeable memory regardless of scope?
It's always safe to add top-level const
to a function argument. This is not even part of the function signature, it just tells the compiler that inside the function body you will not change the parameter to a different value; that in turn lets the compiler catch mistakes where you would reassign the parameter.
Note that when you call send
, the first argument is receiving a copy
of the argument socket
(aka "pass by value"). So it makes no difference whether socket
is or is not in writable memory.