coding style - C++ Picking a type for a constant -


so on regular bases seems find type of constant declared (typically integer, other things strings) not ideal type in context being used, requiring cast or resulting in compiler warning implicit cast.

e.g. in 1 piece of code had below, , got signed/unsigned comparison issue.

static const int max_foo = 16;  ...  if (container.size() > max_foo) {...} 

i have been thinking of using smallest / basic type allowed given constant (e.g. char, unsigned char, const char* etc rather int, size_t , std::string), wondering if idea, , if there places potentially bad idea? e.g. code using 'auto' keyword (or perhaps templates) getting small type , overflowing on appeared safe operation?

going smallest type can hold initial value bad habit. invites overflow.

always code general (which according murphy's law worst) case. templates generalize things, makes worst case lot worse. prepared bizarre kinds of overflows , avoid negative numbers while unsigned types in neighborhood.

std::size_t best choice size or length of anything, reason mentioned. subtract pointers , std::ptrdiff_t instead. recommend cast result of such subtraction std::size_t if can guaranteed positive.

char * not own string in c++ sense std::string does, latter more conservative choice.

this question broad no more specific advice can made…


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -