Not for the first time I see that it is written in the book of shildt:

int max = x < y ? x : y; 

As I understand it, this means that if х less than y , we output x , otherwise y . Then why does he call the max variable? Is this a typo or do I misunderstand the design?

  • five
    Shieldt is a very sloppy author. Plus there may be a translation error. Believe your eyes, not what he writes. - VladD
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

3 answers 3

You pulled the line out of context. Further along the code, this variable is used in the loop condition as a maximum:

 /* Determine if x and v have a common divisor. If so, return least and greatest common factors in the out parameters. */ public bool HasComFactor(int x, int y, out int least, out int greatest) { int i; int max = x < y ? x : y; bool first = true; least = 1; greatest = 1; // Find least and greatest common factors. for (i = 2; i <= max / 2 + 1; i++) { if (((y % i) == 0) & ((x % i) == 0)) { if (first) { least = i; first = false; } greatest = i; } } if (least != 1) return true; else return false; } 

In fact, it is usually customary to name variables according to how they are used, and not how they are initialized.

  • Actually reads like a brain carryover. - hardsky
  • I just do not understand why then in it the minimum of two values, if it is used as a maximum? - Timothy
  • @Timothy, well, it's used like a border in a loop. In this sense, really max. You do not dwell on it, it is important for you to learn the language itself. - hardsky
  • I see, thanks - Timothy

This expression can be written as:

 if(x < y) { max = x; } else { max = y; } 

Logically, we found min. This type of record is very popular and convenient, we replace 8 lines of code with one.

    It says that you, as a programmer on the N line, create the max variable of the int type and initialize it with the return value of the ternary operator whose condition X is less than Y, if the condition is met to return the left side after the "?" if not then right. Well, about the fact that Shild wrote it is necessary to look in the context of the code of his program.

    By the way, using the ternary operator is bad practice because it makes the code more difficult to read, and if we want to be good programmers, then we need to write code that will be understood by other people accompanying this code after you, the only case where you can use the ternary operator is a very simple expression, as in your example)))

    • > bad practice is a very controversial statement. For simple expressions - very good. Because the code should be not only simple, but also as short as possible. Maybe you and the operator ?? never use? - andreycha
    • and you read to the end what I wrote? I said that the ternary operator can be used in simple expressions ... but only in simple ones. - Andrei Pavlyuk