#define SVALUES (1.2, 2.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2, 10, 12, 15, 18, 22, 27, 33, 39, 47, 56, 68, 82)
#define CVALUES (10,15,22,33,47,68)
if(rA == SVALUES){
printf("Ra is a standard value.\n");
}
if(rA != SVALUES){
printf("Ra is not a standard value.\n");
}
if(rB == SVALUES){
printf("Rb is a standard value.\n");
}
if(rB != SVALUES){
printf("Rb is not a standard value.\n");
}
if(c == CVALUES){
printf("c is a standard value.\n");
}
if(c != CVALUES){
printf("c is not a standard value.\n");
}
Asked
Active
Viewed 69 times
-1
-
3Replace `SVALUES` in your code with `(1.2, 2.2, 1.5,....)` and tell if it is a legal C and what it does if it is. Hint: [comma operator](https://en.wikipedia.org/wiki/Comma_operator). – Eugene Sh. Oct 12 '21 at 14:31
-
2What would you expect this to do: `if(c == (10,15,22,33,47,68)) {` ? – Support Ukraine Oct 12 '21 at 14:36
-
1no way I'm aware of to "shortcut" these comparisons. Need to put all those values in arrays (hardcoded, read from file, etc), loop over the arrays and compare each one. [Be mindful of the pitfalls](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) associated with doing exact comparisons on floating point values. Since the values are ordered, you could implement a binary search algorithm, but there's so few values here, not worth it IMO. – yano Oct 12 '21 at 14:41
1 Answers
1
These lines
#define CVALUES (10,15,22,33,47,68)
if(c == CVALUES){
is the same as
if(c == (10,15,22,33,47,68)){
and the (10,15,22,33,47,68)
will give the result 68 due to the way the comma operator works.
So the code is really
if(c == 68){
which is most likely not what you expect.
If you want to check if a specific value is in an array, you need a loop to iterate over the array elements.
Something like:
int CVALUES[] = {10,15,22,33,47,68};
int found = 0;
for (int i = 0; i < sizeof(CVALUES)/sizeof(CVALUES[0]); ++i)
{
if (c == CVALUES[i])
{
found = 1;
break;
}
}
if (found == 1)
{
...
}
else
{
...
}

Support Ukraine
- 42,271
- 4
- 38
- 63