I know this is possible, but is it good practice to use a ternary operator to call functions rather than using an if statement?
if(x){
a();
} else if(y){
b();
} else if(z){
c();
}
Instead do this:
(x) ?
a() :
(y) ?
b() :
(z) ?
c() : 0;
Is there an unknown issues that can occur that I do not know of?
For the nitty-gritty details of how the conditinal operator works, see the C11 Standard, section 6.5.15.
The biggest difference is that the conditional (ternary) operator is meant to be used specifically for assigning to a value. As in,
x = (a < b) ? c : d
If (a < b) is not zero (true), x = c; otherwise, x = d.
There are several constraints on c and d that need to be considered (see 6.5.15.3). Chief among them is that c and d must be one of the following:
Both arithmetic types
Both the same struct or union type
Both void types
Both pointers (or can be converted to such)
Now all of that said, you're specifically not assigning to a variable, but the return values of those functions need to hold to these constraints as well.
However, as was pointed out in the comments on the question - this is still sacrificing readability for terseness. That's almost never best practice.
**Many thanks to #JensGustedt for pointing out the errors in my answer and helping me to fix them!!
Related
I saw this code:
if (cond) {
perror("an error occurred"), exit(1);
}
Why would you do that? Why not just:
if (cond) {
perror("an error occurred");
exit(1);
}
In your example it serves no reason at all. It is on occasion useful when written as
if(cond)
perror("an error occured"), exit(1) ;
-- then you don't need curly braces. But it's an invitation to disaster.
The comma operator is to put two or more expressions in a position where the reference only allows one. In your case, there is no need to use it; in other cases, such as in a while loop, it may be useful:
while (a = b, c < d)
...
where the actual "evaluation" of the while loop is governed solely on the last expression.
Legitimate cases of the comma operator are rare, but they do exist. One example is when you want to have something happen inside of a conditional evaluation. For instance:
std::wstring example;
auto it = example.begin();
while (it = std::find(it, example.end(), L'\\'), it != example.end())
{
// Do something to each backslash in `example`
}
It can also be used in places where you can only place a single expression, but want two things to happen. For instance, the following loop increments x and decrements y in the for loop's third component:
int x = 0;
int y = some_number;
for(; x < y; ++x, --y)
{
// Do something which uses a converging x and y
}
Don't go looking for uses of it, but if it is appropriate, don't be afraid to use it, and don't be thrown for a loop if you see someone else using it. If you have two things which have no reason not to be separate statements, make them separate statements instead of using the comma operator.
The main use of the comma operator is obfuscation; it permits doing two
things where the reader only expects one. One of the most frequent
uses—adding side effects to a condition, falls under this
category. There are a few cases which might be considered valid,
however:
The one which was used to present it in K&R: incrementing two
variables in a for loop. In modern code, this might occur in a
function like std::transform, or std::copy, where an output iterator
is incremented symultaneously with the input iterator. (More often, of
course, these functions will contain a while loop, with the
incrementations in separate statements at the end of the loop. In such
cases, there's no point in using a comma rather than two statements.)
Another case which comes to mind is data validation of input parameters
in an initializer list:
MyClass::MyClass( T const& param )
: member( (validate( param ), param) )
{
}
(This assumes that validate( param ) will throw an exception if
something is wrong.) This use isn't particularly attractive, especially
as it needs the extra parentheses, but there aren't many alternatives.
Finally, I've sometimes seen the convention:
ScopedLock( myMutex ), protectedFunction();
, which avoids having to invent a name for the ScopedLock. To tell
the truth, I don't like it, but I have seen it used, and the alternative
of adding extra braces to ensure that the ScopedLock is immediately
destructed isn't very pretty either.
This can be better understood by taking some examples:
First:
Consider an expression:
x = ++j;
But for time being, if we need to assign a temporarily debug value, then we can write.
x = DEBUG_VALUE, ++j;
Second:
Comma , operators are frequently used in for() -loop e.g.:
for(i = 0, j = 10; i < N; j--, i++)
// ^ ^ here we can't use ;
Third:
One more example(actually one may find doing this interesting):
if (x = 16 / 4), if remainder is zero then print x = x - 1;
if (x = 16 / 5), if remainder is zero then print x = x + 1;
It can also be done in a single step;
if(x = n / d, n % d) // == x = n / d; if(n % d)
printf("Remainder not zero, x + 1 = %d", (x + 1));
else
printf("Remainder is zero, x - 1 = %d", (x - 1));
PS: It may also be interesting to know that sometimes it is disastrous to use , operator. For example in the question Strtok usage, code not working, by mistake, OP forgot to write name of the function and instead of writing tokens = strtok(NULL, ",'");, he wrote tokens = (NULL, ",'"); and he was not getting compilation error --but its a valid expression that tokens = ",'"; caused an infinite loop in his program.
The comma operator allows grouping expression where one is expected.
For example it can be useful in some case :
// In a loop
while ( a--, a < d ) ...
But in you case there is no reason to use it. It will be confusing... that's it...
In your case, it is just to avoid curly braces :
if(cond)
perror("an error occurred"), exit(1);
// =>
if (cond)
{
perror("an error occurred");
exit(1);
}
A link to a comma operator documentation.
There appear to be few practical uses of operator,().
Bjarne Stroustrup, The Design and Evolution of C++
Most of the oft usage of comma can be found out in the wikipedia article Comma_operator#Uses.
One interesting usage I have found out when using the boost::assign, where it had judiciously overloaded the operator to make it behave as a comma separated list of values which can be pushed to the end of a vector object
#include <boost/assign/std/vector.hpp> // for 'operator+=()'
using namespace std;
using namespace boost::assign; // bring 'operator+=()' into scope
{
vector<int> values;
values += 1,2,3,4,5,6,7,8,9; // insert values at the end of the container
}
Unfortunately, the above usage which was popular for prototyping would now look archaic once compilers start supporting Uniform Initialization
So that leaves us back to
There appear to be few practical uses of operator,().
Bjarne Stroustrup, The Design and Evolution of C++
In your case, the comma operator is useless since it could have been used to avoid curly braces, but it's not the case since the writer has already put them. Therefore it's useless and may be confusing.
It could be useful for the itinerary operator if you want to execute two or more instructions when the condition is true or false. but keep in mind that the return value will be the most right expression due to the comma operator left to right evalutaion rule (I mean inside the parentheses)
For instance:
a<b?(x=5,b=6,d=i):exit(1);
The boost::assign overloads the comma operator heavily to achieve this kind of syntax:
vector<int> v;
v += 1,2,3,4,5,6,7,8,9;
How could I achieve something like this ...
int main(void)
{
if (f(x) == (a || b))
{
puts("Success");
}
return (0);
}
This would print Success if the return of f(x) is equal to a or b.
I know it is possible to store it in a variable but my question is:
"Could something like this be done by calling the f(x) function only once without using a variable?"
Edit 1: I'm not allowed to use the switch statement for this assignment
Edit 2: Could I set a range with only one expression like this?
if ( 2 < f(x) < 5)
Would this be valid (return type is int)?
how to test for multiple return values from a function called once without storing into a variable (?)
Not really, but with some restrictions let us abuse C and assume a, b and f() return a character.
1Form a character array made up of a and b and search it using memchr(). Inspired by #David C. Rankin (It does not store the result of f() in a variable, but does call a function)
int main(void) {
// v-------------v compound literal
if (memchr((char [2]){a,b}, f(x), 2)) {
puts("Success");
}
return 0;
}
I see OP added "return type is int" - Oh well.
if ( 2 < f(x) < 5) is valid code, but is does not do what OP wants.
It is like if ( (2 < f(x)) < 5) which compares f(x) with 2 and results in 0 or 1, which is always less than 5.
Tough crowd tonight, so how about the below. Needs a bit of extension math for int overflow`, but is close.
abs(2*f(x) - (a+b)) == abs(a-b)
1 Not serious code suggestions for production code - use a temporary.
This can obviously be done using a switch statement. Another way would be calling a function returning true or false with the first function value as input, another way could be a jump table or even > or bit checking using binary operators depending on a and b values (very common for testing multiple bit flags at once).
But really you shouldn't care about using or not using a variable in such cases. Current compilers are quite good putting temporary variables like that in registers.
EDIT: given the constraints, the most likely solution is using some bit fu, but it fully depends of values of a and b and c, etc. The common way is using powers of two as values to check. Then you can check a set of values in only one operation.
exemple: a = 1, b = 2, c = 4
if (f(x) & (1+2+4)) {...}
checks if we have a or b or c or a superposition of these values.
C language does not such constructs. You need do save the result of the function or/and both a & b.
Of course you can:
int compare(int a, int b, int f)
{
if(a == f || b == f) { puts("Success"); return 0;}
return -1;
}
int f(int x)
{
return x * x;;
}
int main()
{
compare(5,8,f(3));
}
but of course it saves all the values as the functions parameters.
I've been teaching myself in C programming with the book recommended by a friend who is great in C. The book title is "Programming in C" by Stephen Kochan.
I have a background in Java, and I feel a little bit crazy with the way the codes were written in Stephen's book. For example, the following code, in which I commented my confusion. Maybe I'm missing something important here, so I'm looking to hear some inputs about the correct way of coding in C.
#include <stdio.h>
void test(int *int_pointer)
{
*int_pointer = 100;
}
int main(void)
{
void test(int *int_pointer); // why call the test() function here without any real argument? what's the point?
int i = 50, *p = &i;
printf("Before the call to test i = %i\n", i);
test(p);
printf("After the call to test i = %i\n", i);
int t;
for (t = 0; t < 5; ++t) // I'm more used to "t++" in a loop like this. As I know ++t is different than t++ in some cases. Writting ++t in a loop just drives me crazy
{
if (4 == t) // isn't it normal to write "t == 4" ?? this is driving me crazy again!
printf("skip the number %i\n", t);
else
printf("the value of t is now %i\n", t);
}
return 0;
}
// why call the test() function here without any real argument? what's the point?
It is not a call, it is function declaration. Completely unnecessary at this location, since the function is defined few lines before. In real world such declarations are not used often.
// I'm more used to "t++" in a loop like this. As I know ++t is different than t++ in some cases. Writting ++t in a loop just drives me crazy
In this case they are equivalent, but if you think of going to C++ it is better to switch completely to ++t form, since there in some cases (e.g. with iterators) it makes difference.
// isn't it normal to write "t == 4" ?? this is driving me crazy again!
Some people tend to use 4 == t to avoid a problem when t = 4 is used instead of t == 4 (both are valid in C as if condition). Since all normal compilers signal a warning for t = 4 anyway, 4 == t is rather unnecessary.
Please read about pointers then you will understand that a pointer to an int has been passed as an argument here...
void test(int *int_pointer);
You can see the difference between ++t and t++ nicely explained in this link . It doesn't make a difference in this code. Result will be the same.
if(4 == t) is same as if(t == 4) . Just different styles in writing. 4 == t is mostly used to avoid typing = instead of ==. Compiler will complain if you write 4 = t but wont complain if you write t = 4
why call the test() function here without any real argument? what's the point?
Here test is declared as function (with void return type) which expects an argument of the type a pointer to int.
I'm more used to "t++" in a loop like this. As I know ++t is different than t++ in some cases. Writting ++t in a loop just drives me crazy
Note that, when incrementing or decrementing a variable in a statement by itself (t++; or ++t), the pre-increment and post-increment have same effect.
The difference can be seen when these expression appears in a large or complex expressions ( int x = t++ and int x = ++t have different results for the same value of t).
isn't it normal to write "t == 4" ?? this is driving me crazy again!
4 == t is much safer than t == 4, although both have same meaning. In case of t == 4, if user type accidentally t = 4 then compiler would not going to throw any error and you may get erroneous result. While in case of 4 == t, if user accidentally type 4 = t then compiler would through you a warning like:
lvalue is required as left operand of assignment operator.
void test(int *int_pointer); is a function prototype. It's not required in this particular instance since the function is defined above main() but you would need it (though not necessarily in the function body) if test was defined later in the file. (Some folk rely on implicit declaration but let's not get into that here.)
++t will never be slower than t++ since, conceptually, the latter has to store and return the previous value. (Most compilers will optimise the copy out, although I prefer not to rely on that: I always use ++t but plenty of experienced programmers don't.)
4 == t is often used in place of t == 4 in case you accidentally omit one of the =. It's easily done but once you've spent a day or two hunting down a bug caused by a single = in place of == you won't ever do it again! 4 = t will generate a compile error but t = 4 is actually an expression of value 4 which will compare true and assigns the value of 4 to t: a particularly dangerous side-effect. Personally though I find 4 == t obfuscating.
Is there a difference in the order of the comparison operator?
#define CONST_VALUE 5
int variable;
...
if ( variable == CONST_VALUE ) // Method 1
...
OR
if ( CONST_VALUE == variable ) // Method 2
...
Is this simply a matter of preference or is there a compelling reason for a particular comparison order?
The reason some people use method 2 is because you'll get a compiler error if you mistype a = in place of the ==.
However, you'll have people (like me) who will still use method 1 because they find it more readable and if there is an error, it will be detected during testing (or, in some cases, static analysis of the code).
The only difference is that ( CONST_VALUE == variable ) makes the common typo ( CONST_VALUE = variable ) impossible to compile.
By comparison, if ( variable = CONST_VALUE ) will result in the compiler thinking you meant to assign CONST_VALUE to 'variable'.
The =/== confusion is a pretty common source of bugs in C, which is why people are trying to work around the issue with coding conventions.
Of course, this won't save you if you're comparing two variables.
And the question seems to be a duplicate of How to check for equals? (0 == i) or (i == 0)
And here's some more information: http://cwe.mitre.org/data/definitions/481.html
As others mentioned, CONST_VALUE == variable avoids the = typo.
I still do "variable == CONST_VALUE", because I think its more readable and when I see something like:
if(false == somevariable)
my bloodpressure goes up.
The first variant
if (variable == CONST_VALUE)
is better, because it is more readable. It follows the convention (also used in mathematics) that the value that changes most comes first.
The second variant
if (CONST_VALUE == variable)
is used by some people to prevent a mixup of equality checking with the assignment
if (CONST_VALUE = variable)
There are better ways to achieve that, for example enabling and taking heed of compiler warnings.
Others already pointed out the reason. = / == confusion. I prefer the first version because it follows the thought process more closely. Some compiler alleviate the confusion of = and == by giving a warning when it encounters something like
if(a=b)
in this case if you really wanted to do the assignation you're forced to write
if((a=b))
which I would write then as
if( (a=b) != 0)
to avoid the confusion.
This said, we had in our code 1 case where we had a =/== confusion and writing it the other way round wouldn't not have aided as it was a comparison between vars.
What is the meaning of == and how does it differ from =?
How do I know which one to use?
== is a test for equality. = is an assignment.
Any good C book should cover this (fairly early on in the book I would imagine).
For example:
int i = 3; // sets i to 3.
if (i == 3) printf("i is 3\n"); // prints it.
Just watch out for the heinous:
if (i = 4) { }
which is valid C and frequently catches people out. This actually assigns 4 to the variable i and uses that as the truth value in the if statement. This leads a lot of people to use the uglier but safer:
if (4 == i) {}
which, if you accidentally use = instead of ==, is a compile-time error rather than something that will bite you on the backside while your program is running :-)
The logical-or operator is two vertical bar characters, one after the other, not a single character. Here it is lined up with a logical-and, and a variable called b4:
||
&&
b4
No magic there.
a == b is a test if a and b are equal.
a = b is called an assignment, which means to set the variable a to having the same value as b.
(You type | with Shift-\ in the US keyboard layout.)
== tests equality
= assigns a value
neither are related to ||
I might add that in Finnish and Swedish keyboards. Pipe symbol; |; of OR is AltGr (the right alt) and < key. IF you are using Mac on the other hand it is Alt-7 key.
Gave me a lot of sweat when I first started typing on these keyboards.
Now that you know the difference between '==' and '=", let me put you some words of caution. Although '==' is used as a standard test of equality between comparable variables and '=' used as an internally type-casted assignment, the following programming error is quiet common.
In the below example and similar codes, '=' is know as "Always true" conditional operator.
#include<stdio.h>
int main()
{
int i = 10, j = 20;
if ( i = j )
printf("Equal\n");
else
printf("NOT Equal\n");
return 0;
}
So, the word of caution is "Never use '=' in if statements, unless you have something evil in your mind."