Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is bitwise aritmetic on pointers defined behavior?

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;
}
like image 584
Cole Tobin Avatar asked Dec 05 '25 19:12

Cole Tobin


1 Answers

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.

like image 115
Mark Reed Avatar answered Dec 08 '25 12:12

Mark Reed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!