Here is my code:
// defs string untrusted_ip; const char * get_env (const char *name, const char *envp[]); string User::getCommonname(void); void User::setStatusFileKey(string); void User::setKey(string); // 1 if( get_env ( "untrusted_ip", envp ) !=NULL ){ newuser->setStatusFileKey(newuser->getCommonname() +string ( "," ) + untrusted_ip + string ( ":" ) + get_env ( "untrusted_port", envp ) ); newuser->setKey(untrusted_ip + string ( ":" ) + get_env ( "untrusted_port", envp ) ); }else{ newuser->setStatusFileKey(newuser->getCommonname() +string ( "," ) + untrusted_ip); newuser->setKey(untrusted_ip); } // 2 newuser->setStatusFileKey(newuser->getCommonname() +string ( "," ) + untrusted_ip + get_env ( "untrusted_ip", envp ) != (const char*)NULL ? string ( ":" ) + get_env ( "untrusted_port", envp ) : string("") ); newuser->setKey(untrusted_ip + get_env ( "untrusted_ip", envp ) != (const char*)NULL ? string ( ":" ) + get_env ( "untrusted_port", envp ) : string("") ); modified from https://salsa.debian.org/debian/openvpn-auth-radius/-/blob/master/radiusplugin.cpp#L446
block 1 and 2 seems to be equal but 1 works as expected while 2 does not work (seems not executing, for break point is not triggered).
What is the core difference between the two blocks of codes?
Also, only get_env ( "untrusted_ip", envp ) != (const char*)NULL in conditional operator can pass compilation while if( get_env ( "untrusted_ip", envp ) !=NULL ) is possible. What is the reason and are the two problems connected?
P.S. I am using gcc/g++ 10.2.1
T x = E1 ? E2 : E3;the relation and possible conversions betweenE2andE3matter to determine the type of the right hand side of=. Withif (E1) x = E2; else x = E3;relations betweenE2andE3are irrelevant. As a resultxcan potentially be something entierly differentNULLis the old C-compatibility macro for null pointers, in C++ usenullptr. Also don't callget_envmultiple times, call it once and store the result to be reused. And since you have common code in both branches (thegetCommoName()etc.) pull it out to also store in a common variable that can be used and reused.