I’m working on a UDP based file-sharing program. Let me post some sample code before explain the problem.
while (true)
{
Data toRecv;
int bytesRead = recvfrom(s->_UPDsock, (char*)&toRecv, sizeof(toRecv), 0,(SOCKADDR*)&remoteAddress, &remoteAddresslength);
if(bytesRead > 0)
{
string temp(toRecv.chunk,(bytesRead-sizeof(int)));
if(!checker)
{
//total packet amount.
totalChunkAmount = toRecv.ACK;
checker = true;
}
}
}
As you can see at line “13” I’m initializing the totalChunkAmount by using the variable I got from UDP’s recvFrom function. I need to initialize that value only ONCE, that’s why I’m using it inside a bool if() check. and after the initialization, I’m flipping the bool value to true, so it will not be initialized again. Is there any other way to achieve the same result, but not using the ugly bool switching method.
Set
totalChunkAmountto an invalid state before it’s initialized and check for that state. For example iftotalChunkAmountis anintthen,Likewise, if
totalChunkAmountis a pointer then you may set it toNULL(0).[Edit Note: I am just wondering, in your
whileloop mainly you are initializing variable then why don’t yourbreakout of the loop after that ? If you can do so it’s lot more cleaner and no such checks are needed.]