Home > Back-end >  variable decleration inside if - why does it work in c 14?
variable decleration inside if - why does it work in c 14?

Time:12-28

My compiler issues a warning when I declare a variable inside if - but it does compile, even though I use c 14 and not c 17 where this feature is officially introduced.

Code:

#include <iostream>
int foo(){
    return 1;
}

int main(){
    if (int x = foo(); x < 2){
        std::cout << "bla bla\n";
    }
    return 0;
}

Compilation:

g   ./bla.cpp --std=c  14 && ./a.out

Compiler:

g   (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0

Warning:

bla.cpp: In function ‘int main()’:
bla.cpp:6:9: warning: init-statement in selection statements only available with ‘-std=c  17’ or ‘-std=gnu  17’
    6 |     if (int x = foo(); x < 2){
      |  

Does that make sense? Did g 9.4.0 implement a c 17 feature and allow me to use it for c 14 with just a warning?

If this is true, what's the harm of using this in my code? I'm guessing not all compilers will be so leniant, but once the code is compiled by a leniant compiler like mine, the binary will run as I expect, (making this a compilation portablility issue, but no run-time issues), right?

CodePudding user response:

Did g 9.4.0 implement a c 17 feature and allow me to use it for c 14 with just a warning?

Yes.

what's the harm of using this in my code?

Because other compilers may disagree. The same compiler may disagree in newer versions.

Compilers tend to do things like this to make implementing the standard library easier. They may want to replace all of their if statements of the form if((int x = foo())) into if(int x = foo(); x). They simply disable the warning inside of their headers.

But standard library implementations are written against a specific version of the compiler. So they use details of the compiler that others can't reliably use if they want to write portable code. If you're fine with relying on compiler-specific behavior, you can use these things.

  • Related