Thread: macro

  1. #1
    Registered User sballew's Avatar
    Join Date
    Sep 2001
    Posts
    157

    macro

    homework assignment involves defining own macro called
    TOUPPER

    Code:
    #define TOUPPER(c)  ('a' <= (c) && (c) <= 'z' ? (c) - 'a' + 'A' : (c))
    ok I understand the macro itself
    it is checking c to see if it is between 'a' and 'z';
    if so, then it returns the equivalent in uppercase
    if not, then it returns c unchanged


    now we are to find the output of the following code fragment
    assuming s is a string
    assuming i is an int variable

    Code:
    strcpy(s, "rstu");
    i=0;
    putchar(TOUPPER (s[++i]);       /*  call of macro   */
    I run this and get

    U (uppercase U)

    Why???
    Why not uppercase S since incremented before passing???
    Sue B.

    dazed and confused


  2. #2
    Registered User
    Join Date
    Sep 2001
    Posts
    752
    A macro isn't a function, it's inline assembly. You put this into the compuler...
    Code:
    strcpy(s, "rstu");
    i=0;
    putchar(TOUPPER (s[++i]);       /*  call of macro   */
    And your compiler has to read the code twice. First, it goes through and takes care of all the macros and definitions, changing the former code into this...
    Code:
    strcpy(s, "rstu");
    i=0;
    putchar(
    ('a' <= (s[++i]) && (s[++i]) <= 'z' ? 
    (s[++i]) - 'a' + 'A' : (s[++i]))
    );       /*  call of macro   */
    Broke the macro onto several lines for viewability. Hope that doesn't confuse...

    Now, that beast of a line that the preprocessor threw into our putchar is what actually gets compiled, so let's just go through it....
    1. 'a' <= (s[++i]) // ++i, then 'a' <= s[1] TRUE
    2. (s[++i]) <= 'z' // ++ i, then s[2] <= 'z' TRUE
    3. s[++i] - 'a' + 'A' // ++i, then return s[3] - 'a' + 'A', which is U

  3. #3
    Registered User sballew's Avatar
    Join Date
    Sep 2001
    Posts
    157

    Smile I get it !!

    A-ha !!

    I forgot that the incrementation is for each time that [++i] shows up in the argument itself.

    Them thar macros is confusing.

    QuestionC you are the pro. Thanks.
    Sue B.

    dazed and confused


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem building Quake source
    By Silvercord in forum Game Programming
    Replies: 16
    Last Post: 07-11-2010, 09:13 AM
  2. Errors including <windows.h>
    By jw232 in forum Windows Programming
    Replies: 4
    Last Post: 07-29-2008, 01:29 PM
  3. Quantum Random Bit Generator
    By shawnt in forum C++ Programming
    Replies: 62
    Last Post: 06-18-2008, 10:17 AM
  4. Macro Program
    By daspope in forum Windows Programming
    Replies: 5
    Last Post: 04-25-2004, 04:02 AM
  5. about Makefile and Macro
    By tom_mk in forum C++ Programming
    Replies: 1
    Last Post: 09-18-2003, 01:07 PM