Please explain this weird line of code to me | SoloLearn: Learn to code for FREE!

+2

Please explain this weird line of code to me

So I was doing a C++ quiz on the internet, and there was this question: What will be printed by the following code? printf("%d", (int*)2+3); The correct answer is "14 and may depend on platform". I tested it, and indeed it prints 14. But why?

8/12/2017 10:49:12 AM

deFault

2 Answers

New Answer

+7

So we have the expression (int*)2 + 3. The cast takes precedence, so "2" is casted to a pointer to an integer. At this point, (int*)2 = 2. Nothing interesting so far. Here's the thing-- When you increment a pointer, it adds the number of bytes corresponding to the size of the data type that the pointer points to. This makes it easy to work with arrays, for example-- If "x" points to the start of an array (index 0), "x + 1" points to the next element (index 1), and so on. For this to work, the pointer needs to be offset by the size of the data type so it can point to the next element (rather than somewhere in the middle of the same element). On most platforms, the size of an int is 4 bytes (you can check by verifying the output of "sizeof(int)"). So, with that in mind, adding 3 to an integer pointer offsets it by 3 * 4 = 12 bytes. So what we end up with is: 2 + (3 * 4) = 14 The reason this may "depend on platform" is because an int isn't guaranteed to be 4 bytes. It's guaranteed to be at least 2 by the standard, but that's it.

+2

Thanks, Squidy. Awesome answer. I totally forgot about the fact that pointers are incremented by the size of the type they point to.