CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: little question

  1. #1
    Join Date
    Apr 2002
    Location
    Mumbai,India
    Posts
    567

    Question little question

    Dear Friends
    I like to know what will be the o/p of the following code


    ..........
    a[i++] = 3;
    .......

    will the value of 3 goes in i before incrementing or after incrementing.



    also another question is...........

    is there is any difference in comma operator " , " when applied to c and when applied to c++
    i got different answer in c and c++

    Thanks in advance
    vishal

  2. #2
    Join Date
    Nov 2001
    Location
    Beyond Juslibol
    Posts
    1,688
    i will be incremented after.

    if i=2 for example. a[2]=3 is the result and then i will become 3;

  3. #3
    Join Date
    Jun 2001
    Location
    Switzerland
    Posts
    4,443
    Code:
    a[i++] = 3;
    is equivalent to
    Code:
    a.operator[](i++) = 3;
    As you know, the function arguments are fully evaluated before the function is entered, so i++ will be evaluated before assigning 3 to the array element. However, the "return value" of i++ is the previous value of i (because of the postincrement).

    So, 3 goes to the i-th element, and i is incremented "afterwards". If a is an array of built-ins, or of objects that have a natural semantics of operator[], your code is equivalent to (in the absence of exceptions):
    Code:
    a[i] = 3;
    ++i;
    If the operator[] has side effects, or throws an exception, the code snips are not equivalent.

    I am not aware of any difference regarding the comma operator in C vs. C++, but I didn't think of this question in detail.
    Gabriel, CodeGuru moderator

    Forever trusting who we are
    And nothing else matters
    - Metallica

    Learn about the advantages of std::vector.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured