问题描述
#include<stdio.h>
// Pointer To Constant
const int* ptrToConst ;
//Constant Pointer
int* const ConstPtr ;
当我通过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");
}
输出为:
Variable Name: ptrToConst
Is Constant: true
Variable Name: ConstPtr
Is Constant: false
根据输出,将第一个指向常量的变量解析为 constant ,而将另一个变量(常量指针)解析为 constant 。我不了解这种行为,为什么会这样呢? CDT对指针变量的理解是否有所不同?根据我的理解,输出应该恰好相反。
在调试时检查变量d的第二种情况的详细信息:
解决方法
自此(请参阅this answer)
-
const int* ptrToConst
声明(可以修改)恒定整数和 的指针
-
int* const ConstPtr
声明常量指针,该指针指向整数(可以修改),
在第二种情况下,sd.getDeclSpecifier().isConst()
返回false
。
因此,在第二种情况下, const
修饰符可以在pointer operators的抽象语法树的更深中找到(就像您找到了自己)。