Expert C Programming

(Jeff_L) #1

argument char s matches parameter const char p


This is seen throughout all library string functions.


So doesn't argument char argv match parameter const char p?


The answer is no, it does not. It took a little while to answer this question, and it's educational in more
than one sense, to see the process of obtaining the answer. The analysis was carried out by one of
Sun's "language lawyers," [6] and it runs like this:


[6] The New Hacker's Dictionary defines a language lawyer as "a person who will show you the five


sentences scattered through a 200-plus-page manual that together imply the answer to your question 'if only
you had thought to look there.'" Yep! That's exactly what happened in this case.


The Constraints portion of Section 6.3.2.2 of the ANSI C Standard includes the phrase:


Each argument shall have a type such that its value may be assigned to an object with the unqualified
version of the type of its corresponding parameter.


This says that argument passing is supposed to behave like assignment.


Thus, a diagnostic message must be produced unless an object of type const char ** may be


assigned a value of type char **.To find out whether this assignment is legal, flip to the section


on simple assignment, Section 6.3.16.1, which includes the following constraint:


One of the following shall hold:...



  • Both operands are pointers to qualified or unqualified versions of compatible types, and the
    type pointed to by the left has all the qualifiers of the type pointed to by the right.


It is this condition that makes a call with a char argument corresponding to a const char


parameter legal (as seen throughout the string routines in the C library). This is legal because in the
code


char * cp;


const char *ccp;


ccp = cp;



  • The left operand is a pointer to "char qualified by const".

  • The right operand is a pointer to "char" unqualified.

  • The type char is a compatible type with char, and the type pointed to by the left operand
    has all the qualifiers of the type pointed to by the right operand (none), plus one of its own
    (const).


Note that the assignment cannot be made the other way around. Try it if you don't believe me.


cp = ccp; / results in a compilation warning /

Free download pdf