0

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

Anand
  • 2,239
  • 4
  • 32
  • 48
  • 1
    Set a breakpoint in the line with the `for` loop and find out where in the abstract syntax tree (`ast`) the information about the `const` modifier of the second case is hold. – howlger Sep 01 '20 at 12:15
  • I tried it, but I'm not getting such info. Where exactly can we look into it? Have added the screenshot of it, please check. Thank you! – Anand Sep 03 '20 at 12:54
  • 1
    Have you looked into _declarators > [0] > pointerOps_? – howlger Sep 03 '20 at 13:40
  • Just checked, it's coming properly under pointerOps!! Thanks a lot! Could you also please explain the reason? – Anand Sep 03 '20 at 17:50

1 Answers1

1

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).

howlger
  • 31,050
  • 11
  • 59
  • 99