7

I want to convert string constant to preprocessing token using macro. Example:

    // get the first character of marco argument to postfix of new data type.
    #define TYPE(typename) Prefix ## typename #typename[0]
    void main()
    {
        TYPE(int) a, b, c; // Prefixinti a, b, c;
        TYPE(float) x, y, z; // Prefixfloatf x, y, z;
        a = 3;
    }

is it possible in C/C++?
p/s: sorry for my poor English.
edited

4
  • 10
    You can't unstringize, only stringize. Commented May 16, 2013 at 8:04
  • But that should be all you need as long as your constant doesn't contain commas. Commented May 16, 2013 at 8:09
  • 3
    Tried very hard, but can't resist anymore: why do this? Commented May 16, 2013 at 8:09
  • I want to create user-defined data types using X macros. Example: In OpenGL. GLPoint3i, GLPoint3f : get the first character in data type (int ,float) to the postfix for my data types. Commented May 16, 2013 at 8:11

3 Answers 3

4
#define TYPE(first_letter, rest) Prefix ## first_letter ## rest ## first_letter

typedef int TYPE(i,nt);
typedef float TYPE(f,loat);

int main(void)
{
  TYPE(i,nt) a, b, c; // Prefixinti a, b, c;
  TYPE(f,loat) x, y, z; // Prefixfloatf x, y, z;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Do you have a better solution? I want TYPE(int) a, b, c;// Prefixiniti a, b, c;
No, I don't know of another solution.
2

You should alway remeber what the preprocessor does, it modifies your source code before the compiler even sees it.

This does compile( I removed the quotes around int) , but is not so usefull:

#define TYPE(typename) typename

void main()
{
    TYPE(int) a, b, c;
    a = 3;
}

What you are doing results in the following code sent to the compiler:

TYPE("int") a, b, c;

results in"

"int" a, b, c;

where a string constant is followed by a couple of undeclared identifiers, which result in a syntax error

2 Comments

I want to create user-defined data types using X macros. Example: In OpenGL. GLPoint3i, GLPoint3f : get the first character in data type (int ,float) to the postfix for my data types.
I think the openGL variables are created using typedef. have a look at en.wikipedia.org/wiki/X_Macro here you can see how to use X macro,
2

It's not possible, even with templates in C++. By the way, avoid using typename in C-code as it's a keyword in C++ so your C code would be difficult to port.

Also void main() is not strictly portable; use int main() instead.

2 Comments

typename makes no difference since the preprocessor runs before the compiler.
True but still naughty don't you think?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.