I was wondering, is there a flag for the C compiler ( i.e. GCC or GHS) to check whether an input parameters is modified or not?
I mean, if I have the following function, x
and y
may be modified within the function ( as it happening now) if I don't add the const
to them. So I was wondering whether the compiler can detect that situation or not and whether there exists a flag to do so.
int16_t myFunc(int16_t* x ,int16_t* y, bool* e)
{
int16_t z = 0;
z = *x + *y;
*x = 16; // this is wrong on purpose and I would like to detect it
if ( z < 0)
{
*e = true;
}
return z;
}
The only thing you want to do here is use const
like this:
int16_t myFunc(const int16_t* x ,int16_t* y, bool* e)
{
...
*x = 42; // compiler error here
...
}
Here the compiler will issue a diagnostic such as assignment of read-only location '*x'
.
That's what the const
keyword is used for, that's the "flag" you're looking for.
You should put const
on pointer parameters whenever possible. If you know that the object pointed by a parameter won't be modified, use const
.