Conversation
Edited 16 days ago
complaining about C++ again
Show content

the way C and C++ handle pointer addition confuses me. like:

int array[] = {1, 2, 3};
int *arrayPtr = &array;

in this code I think of arrayPtr as a number representing the memory address of array. and given that it’s a memory address, if I add 1 to it it should move 1 byte forward in memory, right? except it doesn’t. if I do that:

arrayPtr += 1;

I just moved 4 bytes forward in memory instead. as in, I increased arrayPtr by 4 because I added 1 to it, because this is an int* and sizeof(int) == 4

if we’re getting as low level as raw memory addresses, why try to abstract away the details of the pointer math? that’s not even an abstraction at that point - that’s just strange counterintuitive behavior. it’s not like it would be that much harder for me to type arrayPtr += sizeof(int); instead of arrayPtr += 1;

2
0
0

@kasdeya eh, i think for convenience, every? language does it this way (pointer arithmetic moves in units of sizeof(T), not bytes). c# and rust (the 2 languages that aren't C/C++ that i'm familiar with) also do that, and i think it would just get annoying if you constantly had to do ptr += amount * sizeof(T).

that would also imply ptr++ moves forward by a byte which is really weird imo. that or value++ is not equal to value += 1.

(but ofc a convenient byte_add should be available for when you do actually need to move forward by bytes)

1
0
0
re: complaining about C++ again
Show content

also I still think the syntax around pointers and arrays is inconsistent and could’ve been done much better. every time I type *var or var[] or &var I feel a little dirty

1
0
0
re: complaining about C++ again
Show content

I would really love if someone made a language that’s as low-level and simple as C, but without all the bad/inconsistent decisions of C. you could probably make this language even simpler than C is tbh because you could avoid all of the bad decisions of C that the language had to be designed around

0
0
0

@5225225 @kasdeya pointer math forwarding in multiples of a byte instead of multiples of the object size would make derefing ptr+1 ub in most cases

also ptr[idx] is equivalent to *(ptr + idx)

0
0
1