-1

Here is a short program I wrote

#include <iostream>
#define test0 "abc"
#define test1 "def"
#define concat(x,y) x##y
int main()
{
  for (int i = 0 ; i < 2 ; ++i)
      std::cout << concat(test,i) << std::endl;
  return 0;
}

But for some reason it doesn't compile (it concatenates i instead of i value), is there a way I can concatenate i's values instead of i's name?

test1.cpp: In function ‘int main()’:
test1.cpp:8:1: error: ‘testi’ was not declared in this scope

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
e271p314
  • 3,581
  • 7
  • 33
  • 56
  • Macros and other preprocessor stuff all happen at *compile-time*, so this is never going to do what you want it to. – Paul R Jan 21 '14 at 17:11

2 Answers2

2

No. Macros are expanded before compilation (hence the term pre-processor), and can only manipulate the tokens that appear in the source code. The value of the variable isn't known until the program is run.

Mike Seymour
  • 242,813
  • 27
  • 432
  • 630
2

No.

The preprocessor (the part of the compiler that handles #define and #include) runs before any other compiler pass, and long before the program ever runs. The variable i will not have a value until the program runs.

Keep in mind that the preprocessor is little more than a text-replace tool for your program source code.

greyfade
  • 24,214
  • 7
  • 64
  • 79
  • Technically, the compiler does a couple of other things first, but it's close enough. http://stackoverflow.com/questions/8833524/what-are-the-stages-of-compilation-of-a-c-program – chris Jan 21 '14 at 17:20
  • Yeah, honestly, I didn't want to get bogged down in character set conversions and tokenization. – greyfade Jan 22 '14 at 01:08