I want to get a filename from the command line or set a default name for that. So, previously I used
static char *fName;
if (argc == 2 ) {
fName = argv[1];
}
else {
fName = "default_file.txt";
}
But for the else
, I get warning: conversion from a string literal to "char *" is deprecated
. If I try something like this:
static char fName [30] = "default_file.txt";
if (argc == 2 ) {
fName = argv[1]; //error
}
Now, I get error: expression must be a modifiable lvalue
. So, how can I fix that?
warning: conversion from a string literal to "char *" is deprecated
This almost certainly means that you are using a C++ compiler. String literals (like "default_file.txt"
in your example) was once of type char[]
in C and C++ both. Writing to a string literal invokes undefined behavior. Because of this, C++ changed the type of string literals to const char[]
. But in C, the type remains char[]
. The warning is therefore an indication that you are using a C++ compiler for compiling C code, which is often not wise.
Note that it is however bad practice in C as well as C++, to have a non-const
-qualified pointer to a string literal.
Now, I get error: expression must be a modifiable lvalue.
Because you can't assign a value to an array in run-time using assignment operators. The C syntax does not allow this. You would have to use memcpy, strcpy or similar.
Corrected code should be something like this:
static const char* fName = "default_file.txt";
if (argc == 2 ) {
fName = argv[1];
}
This is fine for C and C++ both, though in C++ it is recommended practice to use std::string
instead.