Question:
If I have two pointers (essentially a begin
and an end
) which are qualified with restrict
. The begin
pointer is used for dereferencing/reading, and the end
pointer is a one-past-the-end pointer that is never dereferenced and is only used to check the size of the range (via end - begin
). Once the range is consumed I expect begin
and end
to be equal and end - begin
to be 0, though at this point the two pointers will never be dereferenced.
Given restrict
's restrictions on pointers, is it well-defined behavior to subtract and compare these two pointers?
MVCE:
I have some code like the following:
#include <stddef.h>
struct Reader {
const char* restrict data;
size_t size;
};
char read_char(struct Reader* reader) {
--reader->size;
return *reader->data++;
}
int main(int argc, char* argv[]) {
struct Reader reader = {
.data = argv[1],
.size = argv[1] ? strlen(argv[1]) : 0,
};
if (reader.size > 0) {
return read_char(&reader);
}
return 0;
}
I'd like to change it so that instead of having to modify both data
and size
when reading, only data
needs to be modified:
#include <stddef.h>
struct Reader {
const char* restrict data;
const char* restrict end; // Not sure if this should be restrict or not.
};
char read_char(struct Reader* reader) {
return *reader->data++;
}
int main(int argc, char* argv[]) {
struct Reader reader = {
.data = argv[1],
.end = argv[1] + (argv[1] ? strlen(argv[1]) : 0),
};
if (reader.end - reader.data > 0) { // Is this okay?
return read_char(&reader);
}
return 0;
}
Is this permissible, given restrict
's restrictions on pointers?