-4

I'm still trying to figure out macros in C:

#define A(x) #x

int main()
{
    int i = -i;
    char *s = A(i);

    i = -(s[0] == 'i');

    printf("%d", i);

    return 0;
}

Anyone care to enlighten me and comment the code, especially what the macro does and this line: i = -(s[0] == 'i');

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
ran pos
  • 47
  • 4

1 Answers1

7

Read more about the C preprocessor, notably stringification

So A(i) is expanded into "i" literal string (and A(strange !?) would be expanded in "strange !?" , assuming that strange is not some #define-d preprocessor macro). Hence s[0] is 'i', (s[0] == 'i') is true, represented as 1, so the output is -1 ...

You should have compiled your code with all warnings and debug information (gcc -Wall -Wextra -g). Then run in a debugger (gdb) your program step by step.

Notice also that int i = -i; is (as commented by Cool Guy) undefined behavior; you really should be afraid of UB since it can be horrible (even if on my x86_64/Linux machine -with my usual compiler-, in this particular int i= -i; case, it probably won't do a lot of harm, just a tiny bit).

You can also watch the preprocessed form, obtained using gcc -Wall -C -E, in some editor or pager.

BTW your code sample is lacking #include <stdio.h>

PS. I recommend you to install Linux on your laptop and learn to use it (and its compiler) on the command line. Study also existing free software code, you could find good examples of stringification with the C preprocessor.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • Thank you this explains things. I'm using Codeblocks on Windows, so I'm restrained on how much I can do with the compiler. – ran pos Jan 23 '16 at 09:12
  • 1
    Codeblocks is running a compiler command. So just find out what command it is running, and run that command yourself in a terminal. Then, tweak that command to give more warnings, and to show preprocessor output – Basile Starynkevitch Jan 23 '16 at 09:13
  • 1
    @ranpos, then why don't you shift to linux. I used to work on Windows, for some months installed linux on Virtual Box, and finally currently working on a Ubuntu laptop (Also, you can install two OS's on your computer). – Box Box Box Box Jan 23 '16 at 09:14
  • The output when I compile it is -1. since the comparaisins [0] == 'i' is correct, so it outputs 1, plus the sign: i = -(s[0] == 'i'); no? – ran pos Jan 23 '16 at 09:15
  • @ranpos The comparision yields 1 and the unary minus operator makes it -1. – Spikatrix Jan 23 '16 at 09:31
  • 2
    @ranpos BTW, what are you doing here: `int i = -i;`?? That invokes Undefined Behavior. – Spikatrix Jan 23 '16 at 09:32
  • BTW, I also recommend using Linux to learn C or C++ programming (and also to learn programming in general, using other languages, e.g. Scheme & [SICP](https://mitpress.mit.edu/sicp/)...) – Basile Starynkevitch Jan 23 '16 at 15:11