Page 88 - C-Language
P. 88

Some programmers use the strategy of putting the constant to the left of the operator (commonly
        called Yoda conditions). Because constants are rvalues, this style of condition will cause the
        compiler to throw an error if the wrong operator was used.


         if (5 = y) /* Error */

         if (5 == y) /* No error */


        However, this severely reduces the readability of the code and is not considered necessary if the
        programmer follows good C coding practices, and doesn't help when comparing two variables so it
        isn't a universal solution. Furthermore, many modern compilers may give warnings when code is
        written with Yoda conditions.


        Incautious use of semicolons


        Be careful with semicolons. Following example


         if (x > a);
            a = x;


        actually means:


         if (x > a) {}
         a = x;


        which means x will be assigned to a in any case, which might not be what you wanted originally.


        Sometimes, missing a semicolon will also cause an unnoticeable problem:


         if (i < 0)
             return
         day = date[0];
         hour = date[1];
         minute = date[2];


        The semicolon behind return is missed, so day=date[0] will be returned.

        One technique to avoid this and similar problems is to always use braces on multi-line conditionals
        and loops. For example:


         if (x > a) {
             a = x;
         }


        Forgetting to allocate one extra byte for \0


        When you are copying a string into a malloced buffer, always remember to add 1 to strlen.



         char *dest = malloc(strlen(src)); /* WRONG */



        https://riptutorial.com/                                                                               64
   83   84   85   86   87   88   89   90   91   92   93