[C/C++] Programming Challenge - Can you solve it?

AceInfinity

Emeritus, Contributor
Joined
Feb 21, 2012
Posts
1,728
Location
Canada
Requirements: With a variable (char[]) named xy, output the contents of this variable to the console without using the variable directly, or it's memory address, using 2 other variables named x and y. You must use the following 2 lines of code below, and these variables cannot be modified in any way:
Code:
const int x = 0, y = 0;
const char xy[] = "AceInfinity";

Find what would go in place of the ??? in order to output the value of xy to the console:
Code:
std::cout << ??? << std::endl;

You can create a function or do whatever you like as long as you don't modify the variables x, y, or xy, and you don't use the xy variable at all to output it's contents directly. This includes taking a pointer to a significant memory address that would help you read the contents of that variable. In other words, you shouldn't have xy referenced anywhere else in your code, other than where it was declared (from the second line of the 2 required lines of code above).

I will reveal the solution in a while if nobody gets this.

:thumbsup2:
 
Last edited:
Okay..

Code:
#include "stdafx.h"
#include <iostream>

#define GetFunc(x,y) x##y

int main()
{
	const int x = 0, y = 0;
	const char xy[] = "AceInfinity";
	std::cout << GetFunc(x, y) << std::endl;
	return 0;
}
 
Want to explain what is going on behind this?

I have not seen ## used before so I am curious. :grin1:
 
Alright. What's happening here is token concatenation. So taking x and y (note that the values are irrelevant here, only the token's are relevant), and concatenating them together with ## makes them a single token; xy. The ## effectively combines the two tokens into a single token in this macro expansion, assuming each token is valid and contains valid characters..

This can help produce cleaner code when used properly, so it is useful in some cases. For instance;
Code:
#define IDENT(ID)  { #ID, ID ## _id }

struct id identifiers[] =
{
	IDENT (id1),
	IDENT (id2)
};

This would help you avoid having to write out the id name string and identifier out manually; in the case of whatever you're doing with this code.

Code:
{ "id1", id1_id }
...
etc...
 
I looked at this when you first posted it, but had absolutely no idea how to solve it. Interesting solution - I hadn't seen that concatenation before.
 

Has Sysnative Forums helped you? Please consider donating to help us support the site!

Back
Top