Skip to content

__attribute__((cleanup)) on variable declaration in for loop initialization doesn't work correctly in c89/90 #154624

@ahatanak

Description

@ahatanak

clang has an extension that allows variable declarations in initialization statements of for loops before C99. The variable doesn't go out of scope at the end of the for loop.

// This compiles without errors with `-std=c89`.
void foo() {
  for (int i = 1; 0;)
    ;
  printf("i=%d\n", i);
}

However, when the declared variable has a cleanup, the cleanup function is run at the end of the for loop rather than at the end of function foo.

$ cat test.c

#include <stdio.h>

void cleaner(int *a) { printf("run cleanup\n"); }

void foo() {
  for (__attribute__((cleanup(cleaner))) int i = 1; 0;)
    ;
  printf("i=%d\n", i);
}

int main() {
  foo();
  return 0;
}

$ clang test.c -std=c89
$ ./a.out
run cleanup
i=1

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions