Question

I'm checking some OpenCV tutorial and found this line at the beginning (here is the link, code is under the CalcHist section http://opencv.willowgarage.com/documentation/c/histograms.html)

if (argc == 2 && (src = cvLoadImage(argv[1], 1)) != 0)

I've never seen this before and really don't understand it. I checked some Q&A regarding this subject but still don't understand it. Could someone explain to me what is the meaning of this line?

Thanks!

Was it helpful?

Solution

The line does the following, in order:

  1. Tests if argc == 2 - that is, if there was exactly 1 command line argument (the first "argument" is the executable name)
  2. If so (because if argc is not 2, the short-circuiting && will abort the test without evaluating the right-hand-side), sets src to the result of cvLoadImage called on that command-line argument
  3. Tests whether that result (and hence src) is not zero

argc and argv are the names (almost always) given to the two arguments taken by the main function in C. argc is an integer, and is equal to the number of command-line arguments present when the executable was called. argv is an array of char* (representing an array of NULL-terminated strings), containing the actual values of those command-line arguments. Logically, it contains argc entries.

Note that argc and argv always have the executable's name as the first entry, so the following command invocation:

$> my_program -i input.txt -o output.log

...will put 5 in argc, and argv will contain the five strings my_program, -i, input.txt, -o, output.log.

So your quoted if-test is checking first whether there was exactly 1 command-line argument, apart from the executable name (argc == 2). It then goes on to use that argument (cvLoadImage(argv[1], 1))

Checking argc and then using argv[n] is a common idiom, because it is unsafe to access beyond the end of the argv array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top