Reputation: 79
How can I use a continue statement in a ternary operator?
for (i = 0; i < arr_size - 1; i++)
{
ar[i] == 1 || ar[i] == 2 || ar[i] == 3 ? count++ : continue;
}
I can replace it like this.
for (i = 0; i < arr_size - 1; i++)
{
ar[i] == 1 || ar[i] == 2 || ar[i] == 3 ? count++ : count;
}
Upvotes: 0
Views: 1068
Reputation: 1
See this C reference and read n1570 or some newer C standard. Read also Modern C and study for inspiration the source code of existing free software coded in C, such as GNU make.
Code:
for (i = 0; i < arr_size - 1; i++)
{
if (ar[i] == 1 || ar[i] == 2 || ar[i] == 3)
count++;
else
continue;
}
Given that else continue
is the last thing in the loop, you could omit it.
Hint: compile your C code with a recent GCC compiler invoked as gcc -Wall -Wextra -g
.
Read the documentation of your C compiler (e.g. GCC) and your debugger (e.g. GDB).
If so allowed, use static source code analysis tools like the Clang static analyzer, or Frama-C, or Bismon or the DECODER project.
(For both Frama-C and Bismon and DECODER, contact me—in 2021—by email to [email protected].)
Upvotes: 2
Reputation: 34
Ternary operators have some special rules.
For example, you only can use expressions in these three parameters. But continue;
is a complete sentence. So it can't work with ternary operators.
If you have to use ternary operators with continue, you can try this:
for (i = 0; i < arr_size - 1; i++)
{
bool flag = false;
ar[i] == 1 || ar[i] == 2 || ar[i] == 3 ? count++ : (flag = true);
if(flag) continue;
}
Upvotes: 2
Reputation: 224677
You can't use continue
in this way as it is a statement, and the operands of the ternary operator must be a expression.
Like any operator, its result has a value which can be used in other expressions. If it were allowed to use continue
in the way you want, what would the value of the expression be? It doesn't make sense to use in that way.
The ternary operator isn't appropriate for what you want. It should be rewritten as an if
statement:
if (ar[i] == 1 || ar[i] == 2 || ar[i] == 3) {
count++;
}
Upvotes: 5