Let me have a word about this.
The code is so simple that it cannot be made more efficient . A good optimizing compiler from any source design will make almost the same object code. To improve the efficiency of such a simple code manually today is impossible, and even if it were, you should not set such a goal: it is micro-optimization, optimize better at the level of algorithms.
Now about the compactness . What is the purpose of writing more compact code? Efficiency will not add, readability - maybe, yes, and maybe not. More precisely, up to a certain point, a smaller amount of code means greater clarity, but starting from a certain moment clarity is lost. (An example will be at the end.)
So, the only purpose of improving the code may be improving its readability , and hence the likelihood of errors , and ease of support and modification .
Here is my option to improve readability.
enum RussianNumberCase { Single, Some, Many }; RussianNumberCase get_case_for(unsigned int n) { unsigned int lastTwoDigits = n % 100; unsigned int ones = lastTwoDigits % 10; unsigned int tens = lastTwoDigits / 10; // 10..19 have special rules if (tens == 1) return Many; // otherwise, last digit determines the case switch (ones) { case 1: return Single; case 2: case 3: case 4: return Some; default: return Many; } } const char* years(int n) { // таблицу с индексацией пусть за меня построит оптимизатор, // не хочу ухудшать читаемость switch (get_case_for(n)) { case Single: return "год"; case Some: return "года"; case Many: return "лет"; } }
The promised example of how compactness kills code comprehensibility. Compare:
unsigned int SumOfBits(unsigned long long arg) { unsigned int result = 0; while (arg != 0) { unsigned int lastbit = arg & 1; if (lastbit != 0) result++; arg >>= 1; // delete last bit } return result; }
and
int r=0;do r+=arg&1;while(arg>>=1);return r;
"%u"inscanf()refers to the input of variables of typeunsigned int(and you haveunsigned short age). You need to writeif (scanf("%hu", & age) == 1) {... `- For x86 and one variable in the program, this will work. And in other cases - not a fact (it will definitely not work in big-endian architectures (read about the order of bytes )). About the difference in the sizes of variables (2 bytes short and 4 bytes int, I just keep quiet). - avp