I’ve always been under the impression that I shouldn’t define a variable inside of a loop because it’s unnecessary or wasteful. This makes me wonder if the following recv() function needs a fresh buffer for each iteration of the loop:
while (totalBytesRecvd < echoStrLen)
{
char buffer[BUFSIZE];
numBytes = recv(sock, buffer, BUFSIZE - 1, 0);
...
totalBytesRecvd += numBytes;
buffer[numBytes] = '\0';
fputs(buffer, stdout);
}
The documentation for recv() doesn’t mention anything about how it uses the buffer pointer. For a better understanding, I tried defining the buffer just before the loop, and recv() appears to overwrite the buffer, instead of redefining it. Which makes sense since recv() is passed a pointer to the beginning of the buffer.
Is there a specific reason to define a buffer over and over again inside of a loop? Or is my basic understanding of this correct?
recv, asreadand other similar functions, doesn’t care about the previous content of the buffer, it uses it just to write the result.Not that it would make a difference anyway: since you are not initializing your buffer, its content will be “undefined” even if you declare the variable as local to the loop.
Also, on most C implementations:
Obviously, instead, if you initialized your variable it would be different – the code to perform the initialization would have to run at each iteration; but, as said above, there’s no need to initialize anything,
recvjust doesn’t care about the current state of the buffer.