3 ms·
This is valid C and C++.
by bqe 8y ago
This is valid C and C++.
- cyphar 8y agoIt is, but it will always give you a divisor of 1 (because "true" is 1 -- I also thought it would work until I tested it): % cat >division.c <<EOF #include <stdio.h> int main(void) { printf("1/0 = %d\n", 1 / (0 || 1)); printf("1/2 = %d\n", 1 / (2 || 1)); printf("1.0/0 = %f\n", 1.0 / (0 || 1)); printf("1.0/2 = %f\n", 1.0 / (2 || 1)); } % gcc -Wall -o divison divison.c % ./divison 1/0 = 1 1/2 = 1 1.0/0 = 1.000000 1.0/2 = 1.000000 In Python this is not the case: % python3 >>> 1 / (0 or 1) 1 >>> 1. / (0 or 1) 1.0 >>> 1 / (0 or 1) 1 >>> 1. / (2 or 1) 0.5 % python3 >>> 1 / (0 or 1) 1.0 >>> 1 / (2 or 1) 0.5
- int0x80 8y agoWhat do you expect for that C code?
- cyphar 8y agoIn the context of this discussion, the idea was that it would act the same way as Python. But it obviously doesn't.
- user5994461 8y agoIt shouldn't be valid in C++. booleans cannot participate in arithmetic operations. You will get a warning from the compiler if you are lucky. C doesn't have booleans and treat them as integers 0 or 1, it can do the math and will always return 1.
- comex 8y agoThat's not true. C++ does define an implicit conversion from bool to int: https://en.cppreference.com/w/cpp/language/implicit_conversion https://en.cppreference.com/w/cpp/language/implicit_conversi... (under "Integral promotion") And C has a boolean type as of C99.
- comex 8y agoSome trivia: GNU extensions to C/C++ include a "?:" operator that does what you'd want in this case, e.g. x / (divisor ?: 1)