C ++ syntax question

I am working on a UDP based file sharing program. Let me post some sample code before explaining 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 on line "13", I initialize totalChunkAmount using a variable derived from UDP recvFrom . I need to initialize this value only once, so I use it inside the bool if() check. and after initialization, I translate the bool value to true , so it will not be initialized again. Is there any other way to achieve the same result, but not use the ugly bool switch method.

+4
source share
5 answers

Set totalChunkAmount to an invalid state before it is initialized and check that state. For example, if totalChunkAmount is int , then

 totalChunkAmount = -1; // say -1 is invalid value while(true) { ... if(-1 == totalChunkAmount) totalChunkAmount = toRecv.ACK; // ACK can never be -1 } 

Similarly, if totalChunkAmount is a pointer, you can set it to NULL ( 0 ).

[Edit Note: I'm just curious, in your while , you basically initialize the variable, then why did your break the loop after that? If you can do this, it will be much cleaner and no such checks are needed.]

+2
source
 totalChunkAmount = totalChunkAmount == [uninitialized_value_here] ? toRecv.ACK : totalChunkAmount; 
+1
source

The only thing I can think of is to initialize totalChunkAmount to -1 (or some other real world value) and then check this (avoiding the extra bool declaration).

0
source

The code you suggested may be longer, but certainly more readable and simplifies the logic, and I would just leave it as it is.

The only change I will make is to rename the faceless bool checker to bool totalChunkAmountInitialized .

0
source

An elegant solution is to use boost :: optional <>. It is ideal for such occasions and is quite lightweight. If you cannot or do not want to use boost :: you can easily build your own class.

0
source

All Articles