2

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!

Moirae
  • 139
  • 3
  • 14

1 Answers1

5

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.

Chowlett
  • 45,935
  • 20
  • 116
  • 150
  • It's worth pointing out that the "if so" in point 2 refers to the fact that the `&&` operator is short-circuiting, i.e. evaluation will stop if `argc == 2` is false. – unwind May 31 '13 at 10:44
  • Thank you, that helped. It confused me because I've never seen this before. So my next question would be - why to use syntax like this? – Moirae May 31 '13 at 12:44
  • Like which? The use of `argc` and `argv`, or the assignment-then-test of `(src = cvLoadImage()) != 0`? – Chowlett May 31 '13 at 13:22
  • Yes, like that. Can you explain why to use arc and argv, where is the image reading part? – Moirae Jun 03 '13 at 09:53
  • @Moirae - there we go, more deatail on argc, argv added. Does that clear everything up? – Chowlett Jun 03 '13 at 10:31
  • @Moirae - No worries. Remember you can Accept my answer (green checkmark) to say it helped. – Chowlett Jun 04 '13 at 20:26