I'm learning about pointers. Given this code:
FILE* from = fopen("in.txt", "r");
FILE* to = fopen("out.txt", "w");
if (from == NULL || to == NULL)
{
printf("failed to open files!\n");
return;
}
Is changing the if condition to this valid (defined) behavior?
FILE* from = fopen("in.txt", "r");
FILE* to = fopen("out.txt", "w");
if ((from | to) == NULL)
{
printf("failed to open files!\n");
return;
}
No.
First, it shouldn't compile, at least not if the compiler is standards-conformant. Pointers are not valid operands for bitwise operators like | and &.
Second, even if your compiler lets you treat pointers as integers, you risk platform incompatibilities; there are C implementations where they're not at all interchangeable. You might assume any such implementations would necessarily also be conformant, but assumptions are rarely safe...
Third, even assuming that ORing two pointers together works, and gets you something that you can compare with NULL, you've changed the sense of the test: (from|to) will only be NULL if both fopens failed; if just one of them succeeded, the result will be nonzero and your code will fail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With