3.2 - Defining and Differentiating Computation. [] vs ()
I'm trying to get a solid fix on how math computations work in C++ and how to declare their order, in particular with respect to ( ) operators.

this adds to an array:

inventory[numItems++] = "armor".

why don't I need to add () to the calculation? Because it's alone?

inventory[(numItems++)] = "armor"?

I see the () used in a lot of other calculations and I know they have to do with setting order:

num = ((i x 5) + var); //makes sure i is multiplied by 5 before added to var.

Even though the calculation is clear, the entire thing still has to be encasulated within ( ). Right? Why not in the array?

Recommended Answers

All 2 Replies

There is a predefined operator "ranking" which determines the order operators are evaluated in:
http://www.cppreference.com/wiki/operator_precedence

It's basically just like in maths, e.g. products and fractions are evaluated before sums. To change that order, you can use brackets.

In your above example, the brackets are superfluous. This will have the same effect:

num = i*5 + var;

GREAT LINK! Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.