Programming Puzzle Solution

Did you get it?

Let’s first talk about what exactly this expression is doing:

g(a).b[c] = 2;

g is a function that takes some parameter a, and returns a structure with an attribute b, which is an array. In this statement, we’re setting b’s c’th value to 2.

This is useless in C because the structure returned by g will just be thrown away – there are no more references to it.

However, in C++, we have the ability to return references, which are just pointers underneath, using the symbol &. Therefore, the change to the b array would persist, making this a not-so-useless line of code.

What might spark your mind is the normal pointer-based structure variable accessing, which would look like this.

g(a)->b[c] = 2;

This would be useful and work the same way in both C and C++.

 

I hope this puzzle solution satisfied you. If not, I’m thinking of making more programming puzzles. If you’re interested in some of a specific language or technology, leave a comment down below.

 

Dan

359 Total Views 1 Views Today

Leave a Reply

Your email address will not be published. Required fields are marked *