Can I make something very similar, like this?
question ? func1(), val=5 : func2()
I'd like to put more then one instruction on the first or second parameter's place. Is it solvable?
Can I make something very similar, like this?
question ? func1(), val=5 : func2()
I'd like to put more then one instruction on the first or second parameter's place. Is it solvable?
If by "instruction" (which isn't even a thing when it comes to C++'s wording), you mean "expression", then sure: parentheses and the comma operator to the rescue!
SSCCE:
#include <cstdio>
int main()
{
int x = (1, 0) ? 2, 3 : (4, 5);
printf("%d\n", x); // prints 5
}
Yes take a look at the following example:
#include <iostream>
int main()
{
int x,y,z;
double d = 2.5;
auto f = (d == 2.2) ? (x=5,y=10,z=0,2000) : (x=15,y=0,z=20,1000);
std::cout << x << " " << y << " " << z << " " << f << std::endl;
std::cin.get();
return 0;
}
Not so clean so would suggest doing it more readable.
There is a discussion about the ternary operator at http://www.cplusplus.com/forum/articles/14631/ that talks about this. There are some examples in the comments of the discussion showing usage for function calls and multiple ops in the ternary operator. Though, for clarity's sake, it may be best to not do too many things at once in the ternary operator - that can get hard to read pretty quick.
Thanks for these fast and useful answers!
So I programming Arduino in C++, and it is the full example code:
void setup() {
Serial.begin(115200);
bool b = false;
int val = 0;
b ? func1() : (func2(), val = 2);
Serial.println(val);
}
void loop() {}
void func1 (){
Serial.println("func1");
}
void func2 (){
Serial.println("func2");
}
When I learned from this answers, how can I use brackets, and commas correctly, I got these errors:
sketch_jul22a.ino: In function 'void setup()':
sketch_jul22a:8: error: second operand to the conditional operator is of type 'void', but the third operand is neither a throw-expression nor of type 'void'
second operand to the conditional operator is of type 'void', but the third operand is neither a throw-expression nor of type 'void'
I used int type functions instead of void type, and the problem is solved:
int func1 (){
Serial.println("func1");
return 0;
}
int func2 (){
Serial.println("func2");
return 0;
}