What does left-to-right associativity mean?

You normally read left to right. You normally do math left to right. This is left to right associativity and it is most common.

Most people will solve

x = 23 + 34 + 45

by grouping it

x = (23 + 34) + 45

this is left-to-right associativity. You can remember it because you read and do math left to right.

For addition in mathematics it does’t matter too much. You always get the same result either way. This is because addition is associative. To say an operation is associative means left to right and right to left association are the same thing. For addition in programming it still matters because of overflows and floating point arithmetic (but won’t for normal-sized integers in any reasonable language), so when you have a 2 AM bug with large numbers and flippant use of a+b and b+a, remember what order the addition happened in.

In your example:

glm::vec4 transformedVector = translationMatrix * rotationMatrix * scaleMatrix * originalVector

You conceptually chomp through from the right-side first, since that is where the thing you are acting on is. However in C++, * is normally left-to-right associative and it is not possible to override this. glm may handle this in a number of ways: it may build up a cache of things to multiply waiting for the final vector to arrive then do right to left multiplication. It may also (more likely) use the theorem of algebra that matrix multiplication is fully associative, and just multiply out left-to-right, then assure the reader in the documentation that it’s the same as thinking of it as right to left. However, you need to understand the implementation because as previously discussed it matters which way the implementation chooses to multiplying floating point numbers together.

For completeness, consider subtraction. What is a - b - c? Here it really does matter whether it is left or right associative. Of course in math we define it to b (a - b) - c, but some strange programming language might prefer subtraction to be right associative, and take a - b - c to always mean a - (b - c). This alien language had better have a documentation page specifying that - is right-associative, because it is part of the operation specification, not something you can tell simply from looking at the operator’s use.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)