Can I directly use a comparison as an integer in C++?
For example, can I do this?
int var = 0;
for (i=0;i<20;i++){
var += (int)(var < 10);
}
In theory, this will increase var up to a value of 10. I know that it works in Python.
Can I directly use a comparison as an integer in C++?
For example, can I do this?
int var = 0;
for (i=0;i<20;i++){
var += (int)(var < 10);
}
In theory, this will increase var up to a value of 10. I know that it works in Python.
Yes, C++ has implicit casting from bool
to int
.
However, I would suggest you make this a bit more clear that this is your actual intention, so that future readers understand your intent. Explicitly cast it to an int first.
int var = 0;
for (i = 0; i < 20; i++) {
var += (int)(var < 10);
}