What does this operator do in c++?

Viewed 142

What does : do in C++? is there any difference with ? : is it an operator? for example in code below:

    //  Extracting the coefficients and exponents as numbers
    int expon[21] = { 0 };
    int coeff[21] = { 0 };
    for (int i = 0; i < monoms; ++i)
    {
        int monomSize = monomStr[i].size();
        for (int j = 0; j < monomSize; ++j)
        {
            if (monomStr[i][j] == '^')
            {
                expon[i] = stoi(monomStr[i].substr(j + 1, monomSize - j));
                coeff[i] = stod(monomStr[i].substr(0, j));
                break;
            }
        }
    }
    //  Looking for the max of exponents    
    int maxExponent = 0;
    for (int k : expon)                            // <---- **** this colon  ****
        if (k >= maxExponent) maxExponent = k;

    //  Generating the monomials of the null polynomial having 21ree = maxEponent
    std::string newMonom[21];
2 Answers

It is important to recognize the difference between an "operator" and a just piece of syntax that happens to be punctuation. Operators act on expressions to perform some effect that generates a new expression. ; is never an operator; it is simply syntax that specifies when a statement or declaration is over. + is an operator; it acts on two expressions to produce a new one.

Some symbols can be operators in some places but not others. < is an operator... except when the thing right before it is a template-name or the keyword template. In that case, it introduces a set of template arguments/parameters bounded by a closing >.

: is never an operator (even in ?:, it simply acts as the separator between two terms in the ternary expression); it is simply syntax that serves some role in a piece of grammar. In range-based for statements, it separates the declaration for the variable the loop will generate from the range expression that will do the generation. It could have been a keyword, but C++ is kind of allergic to adding new keywords and prefers to use punctuation where possible.

The ?: syntax is called the ternary operator, or also sometimes called the conditional operator.

The : syntax is called a range-based loop.

As for the differences between the two, the conditional operator is sort of a shorthand for if statements. The range-based loop is (as you might guess) a shorthand of sorts for a loop.

Related