Jump to content

Messing with Macros in C

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
helixed

helixed

    Newbie

  • Members
  • PipPip
  • 17 posts
Hello,

I've taken a C class and now I'm trying to learn Objective-C. One of the things we never really covered in class in great detail was the preprocessor. I've ran across a section in my programming book with some interesting things. I've learned I can inject strings into code by doing the following:

#define str(x) # x


str (testing)

Which will cause "testing", included the quotation marks, to be added to my code.

I've also found I can use the ## operator to combine intergers as follows:

#define printx(n)  printf("%i\n" x ## n)


printx(10)

which would expand into:

printf("%i\n", x10);

I was wondering if preprocessor macros could be used to do something like the following:
  • Get an input string from the user.
  • Using a macro, initialize an interger varaible with the name of the variable being the string the user inputed.

For example, if the user were to input "number", the cooresponding line of code would be:

int number;

I would really appreciate any help on this.

Thanks,

helixed

#2
Lance

Lance

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 276 posts
No.

#3
Lance

Lance

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 276 posts
However, if you mean get some input and generate .c or .cpp source file with the input and a template, as in a Visaul C++ Wizard, that's achievable. But I believe that's not what you're talking about, so the answer is NO. period.

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
Macros are processed at compile time, creating a substitution of code. As a result, they do not exist when you get to run time. What happens is this:

Your write this code:
#define printx(n)  printf("%i\n", x ## n)
int i;
int x1, x2, x3, x4, x5, x6, x7, x8, x9;
for (i=1;i<=10;i++)
  printx(i)

The preprocessor will then modify the code to:
#define printx(n)  printf("%i\n" x ## n)
int i;
int x1, x2, x3, x4, x5, x6, x7, x8, x9;
for (i=1;i<=10;i++)
  printf("%i\n",xi)

Then the compiler will run, and produce a compiler error, because variable xi does not exist.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#5
helixed

helixed

    Newbie

  • Members
  • PipPip
  • 17 posts
Okay, thanks for the help everybody.

helixed