Standard practice is to use argv
to access the command line arguments. You may find on some architectures that there are other way of doing this but they are not likely to be portable and there doesn't seem to be much reason here not to go with the standard practice. To read the value into an int you can either use strtol
long n = strtol( argv[1], NULL, 0 );
(note that I tend to prefer using strtol
to atoi
as you've a little more control over the inputs and the error handling - but not much)
You can also use streams as follows:
istringstream ss( argv[1] );
long n;
ss >> n;
Two things do concern me about what you're trying to do though: Firstly you want a variable value, set at runtime to be encapsulated within a function. Logically this will make your code less maintainable as there will be an invisible dependency between your function and an outside influence (a command line parameter) - so the deterministic properties of your function will have been compromised. Practically, this is going to make testing your function far more difficult - especially using automated unit testing as there will be no way of setting the value programatically prior to running it.
Secondly, as if to compound this, you are seeking to restrict scope of the a
variable to compilation unit within the unnamed namespace. This has two undesirable effects. Firstly, no test harnesss or any other code is going to be able to see this variable so again from an automated UT standpoint, this is pretty bad. Secondly, a
becomes effectively a 'global' within your compilation unit. Within functions in this compilation unit, it's going to be quite tricky to follow how and when a
is used meaning a bit of a headache for anyone who maintains your code. I'll assume that you're not using multithreading which would really cause problems.
I'd be interested to know the reasons why you don't want to pass argv[1]
into print_from_external_file()
but I really think that this is the best thing to do. If you don't feel you can pass this variable either directly as a string or converted to an int, you could consider creating a command line parameters or configuration object which could be passed in:
configuration c( argc, argv ); // This contains the hard work of parsing the CL
print_from_external_file( c );
This hides most of the hard work of parsing the command line. Better still it allows you to add real meaning to the CL parameter. Let's say that the a
variable represents a catalog number, the constructor of yourconfiguration
class can simply do this:
configuration::configuration( int argc, char* argv[] )
{
// ...
catalogNo_ = strtol( argv[1], NULL, 0 );
and then if an accessor is added:
int configuration::get_catalog_no() const { return catalogNo_; }
then it becomes much more obvious in print_from_external_file()
what we're doing:
void print_from_external_file( const configuration& c )
{
cout << c.get_catalog_no() << endl;
}