Page 102 - C-Language
P. 102

Note: VLAs are optional as of C11. If your implementation supports C11 and defines the macro
        __STDC_NO_VLA__ to 1, you are stuck with the pre-C99 methods.


        Using character constants instead of string literals, and vice versa


        In C, character constants and string literals are different things.


        A character surrounded by single quotes like 'a' is a character constant. A character constant is
        an integer whose value is the character code that stands for the character. How to interpret
        character constants with multiple characters like 'abc' is implementation-defined.

        Zero or more characters surrounded by double quotes like "abc" is a string literal. A string literal is
        an unmodifiable array whose elements are type char. The string in the double quotes plus
        terminating null-character are the contents, so "abc" has 4 elements ({'a', 'b', 'c', '\0'})


        In this example, a character constant is used where a string literal should be used. This character
        constant will be converted to a pointer in an implementation-defined manner and there is little
        chance for the converted pointer to be valid, so this example will invoke undefined behavior.


         #include <stdio.h>

         int main(void) {
             const char *hello = 'hello, world'; /* bad */
             puts(hello);
             return 0;
         }


        In this example, a string literal is used where a character constant should be used. The pointer
        converted from the string literal will be converted to an integer in an implementation-defined
        manner, and it will be converted to char in an implementation-defined manner. (How to convert an
        integer to a signed type which cannot represent the value to convert is implementation-defined,
        and whether char is signed is also implementation-defined.) The output will be some meaningless
        thing.


         #include <stdio.h>

         int main(void) {
             char c = "a"; /* bad */
             printf("%c\n", c);
             return 0;
         }


        In almost all cases, the compiler will complain about these mix-ups. If it doesn't, you need to use
        more compiler warning options, or it is recommended that you use a better compiler.

        Ignoring return values of library functions


        Almost every function in C standard library returns something on success, and something else on
        error. For example, malloc will return a pointer to the memory block allocated by the function on
        success, and, if the function failed to allocate the requested block of memory, a null pointer. So




        https://riptutorial.com/                                                                               78
   97   98   99   100   101   102   103   104   105   106   107