Home > other >  Can you have multiple getenv in C if statement?
Can you have multiple getenv in C if statement?

Time:09-10

For example this works

#include <iostream>
#include <cstdlib>
 
int main()
{
    if(const char* env_p = std::getenv("PATH"))
        std::cout << "Your PATH is: " << env_p << '\n';
}

but this doesn't

    #include <iostream>
    #include <cstdlib>
  
    int main()
{
    if((const char* env_p = std::getenv("PATH")) && (const char* env_p = std::getenv("PATH")))
        std::cout << "Your PATH is: " << env_p << '\n';
        std::cout << "Your PATH is: " << env_p << '\n';
}

main.cpp: In function 'int main()':
main.cpp:6:9: error: expected primary-expression before 'const'
    6 |     if((const char* env_p = std::getenv("PATH")) && (const char* env_p = std::getenv("PATH")))
      |         ^~~~~
main.cpp:6:9: error: expected ')' before 'const'
    6 |     if((const char* env_p = std::getenv("PATH")) && (const char* env_p = std::getenv("PATH")))
      |        ~^~~~~

How do you check all env parameter exist?

I can do nested if, but that seems ugly

CodePudding user response:

In C 17 you can do this:

if(char const *env1_p = std::getenv("PATH1"), *env2_p = std::getenv("PATH2"); env1_p && env2_p)
{
   std::cout << "Your PATH is: " << env1_p << '\n';
   std::cout << "Your PATH is: " << env2_p << '\n';
}

CodePudding user response:

This has nothing to do with having multiple calls to a function.

The problem is declaring multiple variables. You can't declare multiple variables in an initializer if statement's condition.

if (bool b = true) { ... } // fine
if (bool b = true && bool f = false) { ... } // error

If you have something more complicated than if (type var = expr) then you should not cram the variable declarations into the condition. Use:

const char* env_p1 = std::getenv("PATH1"));
const char* env_p2 = std::getenv("PATH2"));

if (evp_p1 && evp_p2) {

}

CodePudding user response:

You can't declare multiple variables in an if statement's condition using the && operator like that.

You can, however, declare both variables before the condition, like this:

const char* env_p1;
const char* env_p2;
if((env_p1 = std::getenv("VAR1")) && (env_p2 = std::getenv("VAR2"))) {
        std::cout << "Your VAR1 is: " << env_p1 << '\n';
        std::cout << "Your VAR2 is: " << env_p2 << '\n';
}
  •  Tags:  
  • c
  • Related