I had a big reassuring answer to each point raised here and then I realised I was editing your post not quoting it and now I just don't have it in me to type it all out againJomin wrote: ↑Fri Jun 10, 2022 9:28 pmRegarding this function:Code: Select all
char * return_clan_acronym(char * clan_name_string) { #define MAX_ACRO_LENGTH 10 // note 1 char acronym[MAX_ACRO_LENGTH]; //note 2 int words = 1; int i = 0; while (*(clan_name_string + i) != '\0') { //note 3 if (*(clan_name_string + i) == ' ') { // note 4 words++; // note 5 } i++; // note 6 } if (words >= MAX_ACRO_LENGTH) { return "ERROR: Max Length Exceeded.\n"; } else { printf("%s has %i words.\n", clan_name_string, words); } return "Illian Companions"; }
- If you define this function before you use it - i.e. list it above the main(...) one then you do not have to declare it first in this trivial test code...
- You really ought to remove a space around the '*'s that are used to indicate pointer types, either make them butt up against the type declaration (the char) or the variable/function identifier (e.g. the clan_name_string) - leaving it floating in mid-air is just asking for it to be forgotten somewhere - which can have nasty effects!
- as a C "string" is actually a C "array" of "char" type variables - so instead of explicitly showing the pointer arithmetic as "*(clan_name_string + i)" you can be slightly more terse, and conform to what normal{!?} C coders are likely to use as "clan_name_string[ i ]" which means exactly the same IIRC...
- try and "#define" things right at the top of the file where someone else deciphering your code in the far future would generally expect to find such definitions - the thing you are defining will not exist in the file before the point in the file where it is defined and if someone adds some code that uses that which you define before there they literally won't have anything to play with - as the preprocessor will just remove the identifier and replace it with nothing. Whilst this is desirable in some situations - particularly in "header" files where some conditions such as the "Operating System the code is being compiled for" requires such behaviour otherwise such things can lead to gnashing of teeth and wailing.
- an "anti-pattern" I've learn of in the last year or so is that having an "else" part of an "if" after code that always does a "return" if the test is "true" is redundant - and can lead to unnecessary levels of indentation in the source code; e.g. see: https://stackoverflow.com/a/46875487/4805858
