Const Keyword in C and C++ (A few interesting points)

Consider following code snippet. Does it even compile?

foo (const char **conChar) {}

main (int argc, char **argv)

{

foo (argv);

}

This code will not compile with an error message of incompatible type. This is true in both c and c++. (don’t forget to add return type to foo in c++)

Now consider below snippet,

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 */)

here apparently we are doing the same thing while assigning a non const qualified pointer to to a const qualified pointer but it run without an error for both c and c++.

So why the first code is not compiling and second one does?

const char ** denotes a pointer to an unqualified type. Its type is a pointer to a pointer to a qualified type.

Since the types char ** and const char ** are both pointers to unqualified types that are not the same type, they are not compatible types. Therefore, a call with an argument of type char ** corresponding to a parameter of type const char ** is not allowed.

Now what will happen, if I don’t use * or **….?

Consider below code,

int cp ;

const int ccp;

ccp = cp;

You will have compile error in both c and c++ compilers… as you cannot assign a new value to a variable declared const…

Is it really so?

Consider following C code,

int cp = 12;

const int ccp =  10;

int * alter;

alter = &ccp;

*alter = cp;

printf(“value is %d”, ccp);

We can always take address of a const variable in C and can assign it to another pointer variable, which is not a constant pointer. Now we have the access of memory location of the constant variable and can change the value using our pointer.

This is not true in C++ as it prohibits, any kind of assignment to a constant variable.

Advertisements

About Khuram Ali

Programming... Programming and Programming...!!!

Posted on August 7, 2013, in C++ and tagged . Bookmark the permalink. 1 Comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: