how to force compiler error with strcpy() when destination is const

how to force compiler error with strcpy() when destination is const
typescript
Ethan Jackson

How can I make the strcpy() function trigger a compiler error when the destination is a const pointer?

The prototype is strcpy(char *dest, const char *src) however if I specify a const char * for destination, I will see a compiler warning but not a compiler error.

The only means I have found thus far to generate a compiler error is by using defined macro with the C Preprocessor to provide a modified call using strcpy() like so:

#define xstrcpy(dest,src) strcpy((((dest)[0]=0),(dest)), (src))

If I have a simple program containing:

char name1[12] = "jubjub"; const char name2[12] = "bujbuj"; strcpy(name1, "lolo"); // nonconst and works fine xstrcpy(name1, "koko"); // nonconst and works fine strcpy(name2, "lolo"); // const and triggers Warning C4090 'function': different 'const' qualifiers xstrcpy(name2, "koko"); // const and triggers Error C2166 l-value specifies const object

A question about the macro

Is there a problem using a defined macro munging the destination within an expression to test constness and using the comma operator to provide the actual destination pointer to the strcpy() function? The only thing I can come up with is if it's a null or otherwise bad pointer which would fail in strcpy() anyway.

Would this inline correctly if the compiler were to try?

Answer

The C standard says nothing about whether problems are warnings or errors, except for special cases like #error. This is a compiler-specific question.

For GCC and Clang, -Werror turns warnings into errors, and -Werror-SomeName will turn the warning named SomeName into an error. See the warning message to find out its name.

For MSVC, /WX turns warnings into errors, and /wennnn turns warning number Cnnnn into an error.

Related Articles