Thread: Clarification on the expression

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    347

    Clarification on the expression

    i have found the following expression in C
    Code:
    a[i] = i++;
    According to the book it is undefined behavior but little confused why it is so. My interpretation would be something like this
    a. the expression on the right will be evaluated first that is i,
    b. then it would be assigned to a[i],
    c. then i will be incremented.
    What is that i am missing here? Why is it not correct way of writing?

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    When you use post-incrementation on a variable that you use in the same expression multiple times, you invoke "undefined" behavior. Meaning that there's no certain way how this will be resolved. One compiler may decide to do:
    Code:
    a[i] = i;
    ++i;
    while another compiler may do:
    Code:
    temp = i++
    a[i] = temp
    so on and so forth...

    EDIT:
    The reason the post-increment/decrement operators have this behavior is because of their undefined nature, the standard doesn't enforce whether the variable should change right there or after the expression is finished, so the compiler manufacturer picks what suites them best.
    Last edited by GReaper; 04-10-2017 at 06:50 AM.
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    In C, operations are allowed to be performed in any order except where specified by sequence points.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Some clarification please.
    By ShadowBoss in forum C Programming
    Replies: 3
    Last Post: 11-19-2011, 02:23 PM
  2. initializer expression list treated as compound expression
    By karthikeyanvisu in forum C Programming
    Replies: 7
    Last Post: 02-26-2011, 05:19 PM
  3. Replies: 2
    Last Post: 11-25-2009, 07:38 AM
  4. clarification
    By WDT in forum C# Programming
    Replies: 1
    Last Post: 01-21-2009, 01:09 AM
  5. Need a clarification here
    By bithub in forum A Brief History of Cprogramming.com
    Replies: 30
    Last Post: 12-27-2004, 01:06 AM

Tags for this Thread