Thread: Using ## to concatenate tokens

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    144

    Using ## to concatenate tokens

    Hi everyone. I'm trying to get my code to automatically print out string literals called MESSAGE1, MESSAGE2, etc. However, the compiler tells me that it cannot find MESSAGEi. This isn't what I want, obviously. How do I do it properly?

    Richard

    Code:
    #define MESSAGE(i) MESSAGE##i
    #define MESSAGELINES 2
    #define MESSAGE1 "First string"
    #define MESSAGE2 "Second string"
    
    	int i ;
    	for ( i = 0 ; i < MESSAGELINES ; i++ )
    		printf ( "%s" , MESSAGE(i) );
    	return 0;
    ]

  2. #2
    Registered User
    Join Date
    Dec 2008
    Location
    Black River
    Posts
    128
    Token concatenation occurs at preprocessing time. However, you're trying to make up the name by accessing the value of the variable `i', which is unavailable to the preprocessor as it can be only known at runtime.
    Stick close to your desks and never program a thing,
    And you all may sit in the standards commitee!

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    It wouldn't work anyway, because you start i at 0, so you'd be trying to make MESSAGE0 and MESSAGE1, not MESSAGE1 and MESSAGE2.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 0
    Last Post: 11-19-2008, 01:16 AM
  2. copy = concatenate ?
    By Arruba in forum C Programming
    Replies: 3
    Last Post: 11-03-2006, 04:54 PM
  3. Passing pointers to arrays of char arrays
    By bobthebullet990 in forum C Programming
    Replies: 5
    Last Post: 03-31-2006, 05:31 AM
  4. Splitting A String Into Tokens!
    By bobthebullet990 in forum C Programming
    Replies: 15
    Last Post: 03-22-2006, 09:24 AM
  5. How to output tokens in reverse order using strtok
    By Ninz in forum C++ Programming
    Replies: 4
    Last Post: 02-01-2003, 09:00 PM

Tags for this Thread