Search This Blog

Friday, October 1, 2010

An interesting case of typedef!

Consider the following piece of code

typedef char *char_ptr;
const char_ptr p

Now the simple question after this piece of code is-what is constant here,the pointer char_ptr or variable p which is of type

At first sight we jump at conclusion that char_ptr is constant,however the case is little different.

typedef substitutions are not purely textual like that of define.
const int i;
Here,as you can easily conclude i is constant.And same logic applies to the piece of code in discussion.

const can affect a pointer variable in two (or more) different ways: either the pointer can be qualified, or the value pointed to.

int * const p;

the pointer p is qualified, but when you write

const int * p;//or int const *p;

the value pointed to is qualified.

Contrasting with


Now, if you say

#define x int*

and then

const x p;

the result is exactly as if wrote

const int* p;

(due to exact textual replacement in pre-processing)

When you write

typedef int * x;

x is seen as a new type by compiler and interpreted as a pointer to int.
Hence in

const x y;

the variable y is qualified, similar to

const int y;


  1. can u re-write this so that we testers can understand what you have posted here?

    Lol... good work dude..

    How about the Banana-leaf?

  2. is it really confusing??
    bananaleaf is dry fr a while ;)!