Reputation: 2502
I've been working with OpenCV, and some of the example code I've seen uses the following to read in a filename. I understand that argc is the number of command line arguments that were passes, and argv is a vector of argument strings, but can someone clarify what each part of the following line does? I've tried searching this but haven't found many results. Thanks.
const char* imagename = argc > 1 ? argv[1] : "lena.jpg";
Thanks.
Upvotes: 2
Views: 657
Reputation: 226
The example shows the use of the ternary operator.
const char* imagename = argc > 1 : argv[1] : "lana.jpg" By ternary you can say that this expression has three members.
First member is a condition expression
Second member is the value that could be assigned to imagename if conditional expression is true.
Third member is the value that could be assigned to imagename if conditional expression is false.
This example can be translated to:
const char* imagename;
if(argc > 1)
imagename = argv[1];
else
imagename = "lana.jpg";
Upvotes: 1
Reputation: 9671
If argc is greater than 1, assigns to imagename the pointer held in argv[1]
(i.e. the first argument given on the command line); otherwise (argc is not greater than 1), assigns a default value, "lena.jpg".
It uses the ternary operator ?:
. This is used this way: CONDITION ? A : B
and can be read as
if (CONDITION)
A
else
B
So that a = C ? A : B
assigns A to a
if C
is true, otherwise assigns B
to a
. In this specific case, "A" and "B" are pointers to char
(char *
); the const
attribute says we have "strings" that are "constant".
Upvotes: 2
Reputation: 4985
if (argc > 1) {
const char* imagename = argv[1];
} else {
const char* imagename = "lena.jpg";
}
(if we agree that imagename
can go out of the brackets' scope)
Upvotes: 1
Reputation: 49196
const char* imagename = // assign the string to the variable 'image_name'
argc > 1 // if there is more than one cmd line argument (the first is always the program name)
? argv[1] // use the first argument after the program name
: "lena.jpg"; // otherwise use the default name of "lena.jpg"
Upvotes: 6