[Courses] [C] lesson 13: debugging answer
Lorne Gutz
lgutz at vistar.ca
Fri Dec 6 09:20:10 EST 2002
Although the function below works fine and does the job
I would like to make two points:
1. string is a local variable in this function, changes made
here will not alter the variable string in the function that
called it. So rather than introduce another variable 'i', why
not just use 'string' rather than 'string +i' ? Then the line
i++; would become string++; This reduces the complexity
just a little.
2. Functions should have one entery point and one exit. To
accomplish this you will probably require a variable to hold
the return value. Again things will work as written below
but a little self disipline goes a long way in simplifing code.
Picky I know but now is the time you pick up bad habbits that
will turn people off if you are job hunting.
cheers
Lorne
>
> /* Trim newline function:
> * Will trim the newline char in an inputted string.
> *
> * Returns 0 on success, and -1 on failure
> */
> int trim_newline(char *string) {
> unsigned int i = 0;
>
> while(*(string + i) != '\0') {
>
> if(*(string + i) == '\n') {
> *(string + i) = '\0';
> return 0;
> }
>
> i++;
> }
>
> return -1;
> }
> /******* END *******/
More information about the Courses
mailing list