Quantcast
Channel: User Lundin - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 42

Answer by Lundin for K&R Exercise 3-3: Expand Shorthand Notations (e.g. a-d to abcd)

$
0
0

I strongly recommend to avoid K&R since it teaches bad style and is very much outdated. This review will focus on general C programming rather than commenting on your specific algorithm.

Invalid C

  • main() is an incorrect signature, this style went obsolete 23 years ago. You must use int main (void).

Bugs

  • for (i = j = 0; ... then s1[i-1]. This accesses s1 out of bounds at the first lap of the loop.

Dangerous practice

  • char s1[MAXLINE], s2[MAXLINE]; it's not a good idea to allocate arrays of thousands of bytes in local scope - these will end up on the stack and eventually you risk stack overflow. Declaring them as static char s1[MAXLINE] would have avoided that.
  • Incrementing/decrementing loop iterators anywhere else but in the third clause of a for loop is poor and dangerous practice, the code turns completely unreadable when you do. You should reconsider writing this loop differently, as close to the idiomatic for(int i=0; s1[i]!='\0'; i++) as possible.
  • Assignment inside conditions such as c=getchar() inside the 2nd for clause is bad style. K&R does this a lot but it's universally regarded as bad and bug-prone, why all mainstream compilers force an additional parenthesis when you do.

Poor style

  • Avoid declaring multiple variables on a single line, it is harder to read and you can get subtle bugs that way too. Instead, declare each variable on a line of its own.
  • Loop iterators should be declared inside the for loop clause 1 whenever possible - K&R is completely outdated here. That is for(int i=0; ....
  • s1 isn't modified by the expand function so that function should be written with const correctness:
    void expand (const char s1[], char s2[])
  • valid should ideally have been declared as bool.

Viewing all articles
Browse latest Browse all 42

Trending Articles



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