Getting all variable declaration which is inside a loop

Hi everyone,

I want to get all variable declaration which is inside a loop ( whose
scope limited to that loop only). Can someone please tell me how can i do
this?

Ex

int a,bl
for(){
int c,d;
}
Output should be c,d

I’m reasonably sure there is no “magic” way to find this. You can use an AST Matcher to find loops, but you then have to step through the content of the loop. Or you can use a RecursiveASTVisitor, and find the for-statements, then find variable declarations within that, for example using a “map” to track which loop it is that contains what declarations.

RecursiveASTVisitor example:
https://clang.llvm.org/docs/RAVFrontendAction.html

A stack overflow question on using AST Matcher to find loops:
http://stackoverflow.com/questions/36880574/finding-nested-loops-with-clang-ast-statementmatcher

The following matchers should works

varDecl(hasAncestor(whileStmt()))
varDecl(hasAncestor(forStmt()))