Unscrambling C Declarations

This is a Java applet which can unscramble C declarations. The code to parse C declaration is translated from the C code described in K&R, 2nd edition, page 123.

Here are some C declarations from K&R, page 122. Try without the applet first and see if you can unscramble them.

Examples:
    int *f()
    int (*f)()
    char **argv
    int (*daytab)[13]
    void *comp()
    void (*comp)()
    char (*(*x())[])()
    char (*(*x[3])())[5]


Note: It can not handle declarations with function argument types or qualifiers like const, volatile, etc. For example, it can not handle declarations like:

    char * const (a[10]) (int **b)
Therefore, you have to rewrite the declaration to char *(a[10]) ()


Rules for unscrambling

  1. Go to the leftmost identifier and say:
            identifier is
    
  2. Look at left and right side of the identifier and apply the rules of precedence:

          ( )  => [ ] => *
    

    Note: ( ) has the highest precedence and * has the lowest precedence. ( ) and [ ] are used as postfix operators and * is used as prefix operator.

    if you see ( ), say:

        function returning
    
    if you see [ ], say:
        array of
    
    if you see *, say:
        pointer to
    

Example

Here is an example of the above rules. Let's unscramble it:

    char (*(*x[3])())[5]
  1. Go to the leftmost identifier x and we say:

        x is
    

  2. We look at the left and right side of x and see * is at the left side and [] is at the right side. As [] binds tighter than *, we say:

        array [0..2] of pointer to
    

    Now, we see *x[3] is surrounded by () and * is on the left side and () is on the right side. As () has higher precedence than *, we say:

        function returning pointer to
    

    Now, we look again and see, outside the parentheses, the char datatype is on the left side and [] is on the right side. So, we say:

        array [0..4] of char
    

    And we're done. The result is:

    x is array [0..2] of pointer to function returning pointer to array [0..4] of char


Copyright ©1996 Muhammad A. Muquit

I Hate C! Back To CTEC1335