Skip to content

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

@geochip

Description

@geochip

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;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions