I have the following struct in C++:
struct routing_entry {
unsigned long destSeq; // 32 bits
unsigned long nextHop // 32 bits
unsigned char hopCount; // 8 bits
};
And I have the following function:
routing_entry Cnode_router_aodv::consultTable(unsigned int destinationID ) {
routing_entry route;
if ( routing_table.find(destinationID) != routing_table.end() )
route = routing_table[destinationID];
return route; // will be "empty" if not found
}
“routing_table” is a stl::map defined as follows:
map< unsigned long int, routing_entry > routing_table;
My question now is, when using the consultTable function, I want to check that the return value is actually initialized, some how like in Java pseudocode (because I come from the Java camp):
Route consultTable(int id) {
Route r = table.find(id);
return r;
}
then checking if r == null
There are a few problems here. The most urgent may be what happens when the destination ID is not found. Since you have no constructor on the
routing_entryand you are not default initialising, it will have undefined values.One way to handle this is to default initialise. This works by instructing the compiler to fill the structure with zeros. This is kind of a trick borrowed from C but it works well here.
You mention you are coming from Java, unlike in Java, structure and class members are not 0 initialised, so you should really handle that somehow. Another way is to define a constructor:
Also note that in C++, the size of the integer and char members is not defined in bits. The char type is 1 byte (but a byte is a not defined, but usually 8 bits). The longs are usually 4 bytes these days but can be some other value.
Moving on to your
consultTable, with the initialisation fixed:One way to tell might be to check if the structure is still zeroed out. I prefer to refactor to have the function return
boolto indicate success. Additionally, I always typedef STL structures for simplicity, so I’ll do that here:Then we pass in a reference to the routing entry to populate. This can be more efficient for the compiler, but probably that is irrelevant here – anyway this is just one method.
You would call it like this: