On Friday, September 10, 2021 at 11:59:15 AM UTC-3, Andrey Tarasevich wrote:
> On 9/10/2021 7:38 AM, Thiago Adams wrote:
> >
> > It is not clear to me why this static was created and
> > what is the behavior.
> I think it is pretty clearly explained in the standard and elsewhere: to
> help the compiler to optimize the code.
> > For instance,
> > void F(char name[static 10]){
> > }
> >
> > Can I pass a pointer to char*?
> Of course. The parameter type is still `char *`. What prompted the question?
I thought the compiler would ensure the caller is a fixed length array
and emit warnings if not.
> > I will check some compilers to see what is the actual behavior
> >
> > gcc 11.2
> >
> > void f(char name[static 10]){}
> >
> > int main()
> > {
> > char *p = "abc";
> > f(p);
> > }
> > gives me the same warning with our without static.
> >
> > warning: 'f' accessing 10 bytes in a region of size 4 [-Wstringop-overflow=]
> >
> > no warning here
> >
> > void f(char name[static 10]){}
> >
> > extern char* s1;
> > int main()
> > {
> > f(s1);
> > }
> >
> For obvious reasons, the compiler was "smart enough" to issue the
> warning in the first case. In the second case it is simply impossible.
>
> This feature will produce a tangible difference in code generation. For
> example, such parameter cannot be null. For example, Clang will
> aggressively discard branches that would've been taken for a null parameter
>
>
https://godbolt.org/z/Y5KKzPbv8
Interesting but the code doesn't look much realistic.
if we take a real function like:
int strcmp ( const char * str1, const char * str2 );
it could be:
int strcmp ( const char str1[static 1], const char str2[static 1]);
but the generated code is the same because strcmp is already
considering that str1 and str2 are not null.
It would be nice to have static analysis checks but I believe compilers like
gcc already do it independently of the [static ].
So the feature is still confuse.
It is a better contract but how to use this in a practical way?
Here there are interesting comments referring to MISRA.
https://rules.sonarsource.com/c/RSPEC-1831
" Therefore, in practice the use of static on an array parameter’s size merely
lends a false sense of security, and static should not be used in this context."
I think if the behavior were only accept fixed length arrays that we can check
100% it would be a more useful feature. In the worst it is just a matter of create
two versions of the same function.
itoa could be a sample of that.
Let's say we have a itoa10 for instance for radix 10 it could ask a fixed length buffer
for input.