It looks I don't familiar with CPP standards much and I run into this problem today.
x=a+b?c:d;
It's a conditional assignment mixed with other operator in one statement. x is always c or d. a is always ignored. At least for gcc version 4.9.2 (Ubuntu 4.9.2-10ubuntu13). No warnings are given during compilation.
I think there is no check for that in cppcheck. Perhaps someone could add it?
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
Hm, then it wasn't the ignorance of a but I wasn't familiar with order of operator precedence for ?:.
I tried your code - build it with gcc version 4.9.2 (Ubuntu 4.9.2-10ubuntu13). And got output:
3
4
Then I replaced int x = a + b?c:d; with int x = a + (b?c:d);. And got
3
2
So a+b?c:d is processed as (a+b)?c:d which I didn't expect.
I would wish to get a warning from gcc on that during compilation. It barks on every else without {}.
How do you think, is it only me or it has sense to add such warning to cppcheck?
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
Cppcheck should warn about this. Have you tried using --enable=style? Then maybe something in your code confuses Cppcheck, then we want to fix it.
$ cat 123.c
int f(int a, int b){
int ret= a + b ? 123 : 456;return ret;}
$ ./cppcheck --enable=style 123.c
Checking 123.c...
[123.c:2]: (style) Clarify calculation precedence for'+' and '?'.
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
It looks I don't familiar with CPP standards much and I run into this problem today.
It's a conditional assignment mixed with other operator in one statement.
x
is alwaysc
ord
.a
is always ignored. At least forgcc version 4.9.2 (Ubuntu 4.9.2-10ubuntu13)
. No warnings are given during compilation.I think there is no check for that in cppcheck. Perhaps someone could add it?
Why do you think a is always ignored?
In the following example you can see the results depends on a:
You might check out http://en.cppreference.com/w/cpp/language/operator_precedence which explains the rules of operator evaluation.
Hm, then it wasn't the ignorance of
a
but I wasn't familiar with order of operator precedence for?:
.I tried your code - build it with
gcc version 4.9.2 (Ubuntu 4.9.2-10ubuntu13)
. And got output:Then I replaced
int x = a + b?c:d;
withint x = a + (b?c:d);
. And gotSo
a+b?c:d
is processed as(a+b)?c:d
which I didn't expect.I would wish to get a warning from gcc on that during compilation. It barks on every
else
without {}.How do you think, is it only me or it has sense to add such warning to cppcheck?
Cppcheck should warn about this. Have you tried using --enable=style? Then maybe something in your code confuses Cppcheck, then we want to fix it.