Search code examples
eclipseeclipse-cdt

Eclipse CDT isConst check


I have a simple Pointer.c file:

#include<stdio.h>

// Pointer To Constant
const int* ptrToConst ;


//Constant Pointer
int* const ConstPtr ;

When I parse it through Eclipse CDT:

File f = new File("C:/Data/Pointer.c");
IASTTranslationUnit ast = ASTProvider.getInstance().getASTWithoutCache(f);

for (IASTDeclaration d : ast.getDeclarations()) {

  IASTSimpleDeclaration sd = (IASTSimpleDeclaration) d;
  System.out.println("Variable Name: " + sd.getDeclarators()[0].getName());
  System.out.println("Is Constant: " + sd.getDeclSpecifier().isConst() + "\n");
}

The output is:

Variable Name: ptrToConst
Is Constant: true

Variable Name: ConstPtr
Is Constant: false

As per the output, the first variable which is pointer to constant is parsed as constant while the other one, a constant pointer is not. I don't understand this behavior, why is it so? Does CDT understand the pointer variables differently? As per my understanding the output should be the exactly reverse of it.

Check the variable d detail for 2nd case at the time of debugging:

enter image description here


Solution

  • Since (see this answer)

    • const int* ptrToConst declares a pointer (that can be modified) to a constant integer and
    • int* const ConstPtr declares a contant pointer to an integer (that can be modified),

    in the second case sd.getDeclSpecifier().isConst() returns false.

    So in the second case, the const modifier can be found deeper in the abstract syntax tree at the pointer operators instead (as you have found out yourself).