As far as I know, you cannot modify a Array variable
How come this code run without any error. Is there anything I am missing out here. (It's not about why there is 'L-VALUE REQUIRED' error , it's about why there isn't.)
#include<stdio.h>
int strlens(char *s);
void main(){
char s[]="get me length of this string ";
// s++ ; this would give 'L-VALUE REQUIRED ERROR'
printf("%d",strlens(s));
}
int strlens(char s[]){
int i;
for(i=0; *s!='\0';++i, ++s) ; //++s: there is NO 'L-VALUE REQUIRED ERROR'
return i;
}
A quirk of the C language that is well-known to seasoned C programmers, but trips up new C coders to no end, is that arrays are "pass by reference". Generally speaking, an array name used in most expressions will "decay" to the address of its first element. Functions carry that to an extreme case, where the array syntax in the function parameter is actually an alias for the pointer type itself.
This is described in paragraph 7 of c11's §6.7.6.3 Function declarators:
A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the
[
and]
of the array type derivation.
Historically, this quirk was an attempt to maintain behavioral compatibility to C's predecessors, B and BCPL, and efficient structure layout. C's predecessor had a semantic for arrays in that its physical layout was actually a pointer that got dynamically allocated and initialized at runtime. When passed to a procedure, the pointer semantic was a natural adoption. Dennis Ritchie invented the notion of allowing the array syntax represent the actual address of the array, and then maintained the pointer semantic when passed to a function. Thus, the inventor of the C language considered this quirk a novel solution to a real world problem (semantic compatibility).
References: The Development of the C Language