Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generates incorrect code when variable is declared in the while loop parentheses #678

Open
geochip opened this issue Dec 13, 2024 · 0 comments

Comments

@geochip
Copy link

geochip commented Dec 13, 2024

Example:

#include <cstdio>

int next() {
    static int i = 1;
    return i++;
}

int main() {
    while (int i = next()) {
        printf("i=%d\n", i);
        if (i >= 10) {
            break;
        }
    }
}

The generated code is:

#include <cstdio>

int next()
{
  static int i = 1;
  return i++;
}

int main()
{
  while(static_cast<bool>(i)) {
    printf("i=%d\n", i);
    if(i >= 10) {
      break;
    } 
    
  }
  
  return 0;
}

It does not compile, because i is not declared. Also the call to next() is omitted.

test.cpp: In function ‘int main()’:
test.cpp:11:27: error: ‘i’ was not declared in this scope
   11 |   while(static_cast<bool>(i)) {
      |                           ^

The expected result would be, for example, to create a local scope and a variable in the local scope (similar to what compiler does) and to not omit the call to next(). Something like this:

#include <cstdio>

int next()
{
  static int i = 1;
  return i++;
}

int main()
{
  {
    int i;
    while(static_cast<bool>(i = next())) {
      printf("i=%d\n", i);
      if(i >= 10) {
        break;
      } 
      
    }
    
  };
  return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant