What is considered best practice when referring to a program's name? I've seen:
#define PROGRAM_NAME "myprog"
printf("this is %s\n", PROGRAM_NAME);
as well as:
printf("this is %s\n", argv[0]);
I know, that the second approach will give me ./myprog
rather than myprog
when the program is not called from $PATH
and that the first approach will guarantee consistence regarding the program's name.
But is there anything else, that makes one approach superior to the other?
You need an array: char name[32]; or similar (and should use %31s in the format to avoid overflows). Also, with an array, you'll use just name (and not &name ) in the call to scanf() . And you should check that scanf() succeeded: if (scanf("%31s", name) == 1) printf("Your name is %s\n"); — adding a newline too.
C Style Guidelines. Meaningful names for variables, constants and functions. Do not use camelcase; use underscores for multi-word variables. For example, use hot_water_temperature instead of hotWaterTemperature.
In C/C++, the # sign marks preprocessor directives. If you're not familiar with the preprocessor, it works as part of the compilation process, handling includes, macros, and more. It actually adds code to the source file before the final compilation.
The second approach is superior when you have multiple links. In *nix systems, sometimes behavior depends on how you call a program. So hard coding the program name would clearly be a problem -- it could never check that.
I tried to take the best of both worlds:
char const * program_name;
int main(int argc, char **argv) {
program_name = argv[0];
//...
}
If you need program_name to be available in some other file you can declare it like this:
extern char const * program_name;
I declare "char const *" because I want it to be a pointer which points to const data. I'm not sure if I did right this part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With