-2

so i have this linear search code, mostly i know everything that happens in that code. But now I struggle at the end... I tried to google it but somehow did not find anything....

Here is the Code

#include <iostream>
using namespace std;



int search(int k, int array[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        if (array[i] == k)
            return i;
    return -1;
}

int main(void)
{
    int array[] = { 2, 3, 4, 10, 40 };
    int k = 10;
    int size = sizeof(array) / sizeof(array[0]);
    cout << size << endl;

    int result = search(k, array, size);
    (result == -1)
        ? cout << "K gibt es nicht"
        : cout << "K Gefunden: " << result;
    return 0;
}

So my question.. What does the : and the ? before the cout mean?

? cout << "K gibt es nicht"
: cout << "K Gefunden: " << result;
Jarod42
  • 203,559
  • 14
  • 181
  • 302
dudewhelp
  • 1
  • 3
  • 7
    Look at [ternary operator](https://en.cppreference.com/w/cpp/language/operator_other#Conditional_operator). – Jarod42 May 04 '21 at 15:11
  • 2
    I would use a simple `if` here BTW: `if (result == -1) { std::cout << "K gibt es nicht"; } else { std::cout << "K Gefunden: " << result; }` – Jarod42 May 04 '21 at 15:13
  • 3
    dupe of [What does '?' do in C++?](https://stackoverflow.com/questions/795286/what-does-do-in-c) or many others, e.g. search for _stackoverflow c++ question mark colon_ – underscore_d May 04 '21 at 15:14
  • 4
    On a side note, that's abusing the poor conditional expression. – molbdnilo May 04 '21 at 15:18

1 Answers1

-4

It's the ternary operator, which is short hand notation for an if, else statement.

Before the ? is the operated which is evaluated as a true/false value.

? the code after is executed if the operand evaluates to true. : the code after is executed if the operand evaluates to false.

So

 (result == -1)
        ? cout << "K gibt es nicht"
        : cout << "K Gefunden: " << result;

is short hand for:

if(result == -1) {
 cout << "K gibt es nicht";
} else {
  cout << "K Gefunden: " << result;
}
Alan
  • 45,915
  • 17
  • 113
  • 134
  • 4
    ternary operator yields in *expression*. *if-statement* is.. a *statement*. – Jarod42 May 04 '21 at 15:15
  • 6
    In general, this answer is too shallow, to the point of glaring over quite important details. Ternary operator in general is not a short hand notation, it has distinct properties. There is already a duplicate to the question. – SergeyA May 04 '21 at 15:15
  • @Jarod42 Ah yes, how many C++ programmers does it take to program a lightbulb... – Alan May 04 '21 at 15:22