Why can't strings have some pre-allocated bytes in C for storing the length?
18 hours ago, Gat Pelsinger said:In C, we need to use strlen to get the length of the string because the null terminator which marks the end of the string is placed at the last. Wouldn't it have been better to have a few pre-allocated bytes of data at the start of the string which could store the string's length?
Well it's like @Eigenvektor pretty much said.
To add to that concept though, it adds overhead then (and forces that overhead onto people). If you really needed that sort of thing, you could easily just store it as a struct yourself.
Traversing a list actually has minimal time penalty compared to the likelihood of needing the length. i.e. if you are trying a strcmp, you still need to loop the entire string...except now instead of just passing in a pointer to the string, you have to deal with passing a struct (which would take up 2 registers) or a pointer to the struct, and then you would have to dereference to get the pointer to the string.
Overall the above would add overhead (both in memory and CPU cycles) for no benefit.
Many of the string functions would then also behave that way, where you essentially are sacrificing the performance for the sake of knowing the length of the string.
You get into even more "inefficiencies" as well when you are working with constant strings and doing manipulation as such.
const char* quickexample = "abcdefghijklmnopqrstuvwxyz"; const char* target = "ground"; const char* somefunction() { const char* qe = quickexample; while(*qe != '\0' && cmp(eq, target) < 0) qe++; return qe; }
So notice the above, it's working on the raw string, if strings were required to have length, you wouldn't be able to do something like above...instead you would have to create a new string each time and do the comparison. It gets worse since there is a const char*...so it gets trickier as well since lots of strings can be const as well...which makes passing it as a struct harder as well because then you have to effectively copy it each time.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now