Comma operator in a macro-help me understand this plz!!

Discussion in 'C Programming' started by s.subbarayan, Jul 5, 2004.

  1. s.subbarayan

    s.subbarayan Guest

    Dear all,
    What does this following piece of code do?


    #define CONVERT_SELF_PTR(type,in,out) \
    (((in) != NULL) ? ((out) = (type *)(in), RETURN_OK) : ERROR_PARAM)

    especially can someone let me understand why theres a comma in between

    (out) = (type *)(in) and RETURN_OK in the expression ((out) = (type
    *)(in), RETURN_OK)?

    It will be also helpful if you could let me know the sequence in how
    this expression in whole will be evaluated in steps.

    Expecting all your help and advanced thanks for the same.

    Regards,
    s.subbarayan
     
    s.subbarayan, Jul 5, 2004
    #1
    1. Advertisements

  2. s.subbarayan

    Richard Bos Guest

    That's just an ordinary comma operator. It works as any other comma
    operator does: it separates successive expressions, returning the value
    of the last expression as the value of the whole.
    Just peel it off into parts:

    (in)!=NULL?
    (
    out=(type *)in,
    RETURN_OK
    )
    :
    ERROR_PARM

    That is, it first checks to see whether in is a null pointer. If not, it
    casts null to a pointer of type "type" and assigns it to out; and then
    evaluates RETURN_OK (which presumably is a single value), and returns
    that as the value of the whole expression. If in _is_ a null pointer,
    the entire macro evaluates to ERROR_PARM.
    No, I can't think of a good reason for writing a macro like that,
    either. The context in which you found it might provide an explanation.

    Richard
     
    Richard Bos, Jul 5, 2004
    #2
    1. Advertisements

  3. (s.subbarayan) ask:
    Assuming in particular that RETURN_OK and ERROR_PARAM are distinct
    constants, and NULL has its usual meaning, a most natural explanation
    is that
    - out is expected to be a pointer to type
    - in is expected to be a pointer
    - the macro checks if in is a non-NULL pointer, and returns a
    status accordingly; and in the affirmative only, copies
    in to out, with type cast.

    The comma is here to execute the assignment and produce RETURN_OK
    in the second case; this is done so that the macro behaves
    somewhat like a function.


    For example

    unsigned char *myin;
    char *myout;

    if (CONVERT_SELF_PTR(char,myin,myout) != RETURN_OK)
    printf("error\n");

    means

    if (myin==NULL)
    printf("error\n");
    else
    myout = (char *)myin;



    Fran├žois Grieu
     
    Francois Grieu, Jul 5, 2004
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.