Y
Ya Shou
Hello,
I want to assign an uncertain value to a variable, this variable with
values in the configuration file, reads the configuration file
through a function to return to the read configuration value, if not
configured or the value of non-compliance, will return 0 for failure,
when this, I will to give it a default value assigned.
However, I found it seem impossible to achieve this in C, but much
easier to implement in Perl, see below:
cfgval = loadConfig () || DEFAULT_VAL;
In C '||' operator does not return the value of the expression which
is true, but returns 1 or 0, so that I can not be used in a similar
way. I considered a program in C is:
cfgval = loadConfig ()? loadConfig (): DEFAULT_VAL;
And however, this approach to involve a duplication of code, it is
ugly, the other will call loadConfig function twice, inefficient and
likely to cause unnecessary accidents.
Of course, if / else statement can achieve this functionality, but
this method requires an additional variable, and not look simple. As
follows:
int loadval = loadConfig ();
if (loadval! = 0) {
cfgval = loadval;
} else {
cfgval = DEFAULT_VAL;
}
Or
int loadval;
cfgval = (loadval! = 0)? loadval: DEFAULT_VAL;
I would like to ask you is, in this case, there is nothing more
beautiful realization?
Thanks.
I want to assign an uncertain value to a variable, this variable with
values in the configuration file, reads the configuration file
through a function to return to the read configuration value, if not
configured or the value of non-compliance, will return 0 for failure,
when this, I will to give it a default value assigned.
However, I found it seem impossible to achieve this in C, but much
easier to implement in Perl, see below:
cfgval = loadConfig () || DEFAULT_VAL;
In C '||' operator does not return the value of the expression which
is true, but returns 1 or 0, so that I can not be used in a similar
way. I considered a program in C is:
cfgval = loadConfig ()? loadConfig (): DEFAULT_VAL;
And however, this approach to involve a duplication of code, it is
ugly, the other will call loadConfig function twice, inefficient and
likely to cause unnecessary accidents.
Of course, if / else statement can achieve this functionality, but
this method requires an additional variable, and not look simple. As
follows:
int loadval = loadConfig ();
if (loadval! = 0) {
cfgval = loadval;
} else {
cfgval = DEFAULT_VAL;
}
Or
int loadval;
cfgval = (loadval! = 0)? loadval: DEFAULT_VAL;
I would like to ask you is, in this case, there is nothing more
beautiful realization?
Thanks.