Quantcast
Channel: Microcontrollers
Viewing all articles
Browse latest Browse all 251352

Forum Post: RE: CCS/TM4C1294NCPDT: Local Structure requires initialization to 0, otherwise returns NaN

$
0
0
[quote user="Bruno Saraiva"]Being a local structure, I would expect the compiler to initialize it to zero automatically[/quote] That expectation would be wrong. Only global and static variables are initialized. Automatics are not. This is part of standard C (has been since K&R I) [quote user="Bruno Saraiva"] memset (&average, 0, sizeof(sensorData_t));[/quote] Note that while practically this will work, it is not guaranteed to do so. There are several ways in which it can fail. Those would generally need an obscure architecture to do so although floating point is a more likely sensitive point. The ARM architecture and tools are not AFAIK subject to those areas that could make it fail. [quote user="Bruno Saraiva"]The second option seems cleaner, but require that we "count" the number of elements, and that we revisit the function if something is added to the structure. [/quote] C++ is at an advantage here, but is there any reason to initialize average at all? You only use a subset of the fields, just make your loop one smaller and rather than add assign the first value. only subsequent values get added A few other notes validNumber is a global and should probably be passed instead You are creating a potentially large temporary only to copy it over the original, in the process destroying your original data and potentially creating a memory leak potentially employing a lengthy copy It would make more sense simply to compute the averages in the first original structure would it not? Might it make more sense to create a structure to hold the average and return it rather than include the rest of the fields in the passed structure? You could even use it as one of the members in the original structure. You call this an average but it's actually a summation. Probably not an effect to worry about but adding values together eventually fails, perhaps more subtly for floating point Robert

Viewing all articles
Browse latest Browse all 251352

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>