#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Posts
    16
    Rep Power
    0

    Increment(++) and Decrement(--) Operators in C


    Hi everyone....Whenever I solve the questions on inc (++) and dec (--) operators in C, I get confusing and surprising results. After solving some questions I thought I got the concept of these operator but soon I find my self wrong with a new shocking answer. Well all and all I find this topic a very tricky one.So please tell me its concept with some example. Appreciate your help.
  2. #2
  3. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,021
    Rep Power
    1285
    Originally Posted by anilkumartgsb
    Hi everyone....Whenever I solve the questions on inc (++) and dec (--) operators in C, I get confusing and surprising results. After solving some questions I thought I got the concept of these operator but soon I find my self wrong with a new shocking answer. Well all and all I find this topic a very tricky one.So please tell me its concept with some example. Appreciate your help.
    Can you list the problems you were trying to solve?
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,841
    Rep Power
    480
    int i = 8;

    expression involving ++i

    You are assured that i is incremented and the new value is used in the expression. C may otherwise freely rearrange the computation according to precedence rules.


    expression with i++

    The expression computes with current value of i and sometime later increments the value of i.

    Therefore, do not try such expressions as
    i++/++i
    f(i++,--i,++i,i++,i--)/i--;
    where the result depends on knowing when the incrementations occur, because this varies by compiler and optimization level and in every other way permitted by the c standard.
    Last edited by b49P23TIvg; January 9th, 2014 at 09:57 AM.
    [code]Code tags[/code] are essential for python code and Makefiles!
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Posts
    16
    Rep Power
    0
    Yes @b49P23TIvg I got some errors in these type of questions, when I solve these questions theoretically I got some diff ans and when I run it on C compiler I got strange and surprising answers thats make me confused. Well thanks for your help I keep in mind this concept about the compilers.
  8. #5
  9. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,841
    Rep Power
    480
    theoretically there isn't a correct answer.
    the answer is undefined.
    it's not about the compilers.
    the c standard permits many answers.
    [code]Code tags[/code] are essential for python code and Makefiles!
  10. #6
  11. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,109
    Rep Power
    1802
    It is quite simple. If you only ever write expressions of the form:
    Code:
    i++ ;
    i-- ;
    ++i ;
    --i ;
    they are clear and unambiguous. Anything else should be avoided for reasons of clarity as much as correctness. If anything is to be learned from expressions such as :
    Code:
     x = (i++,--i,++i,i++,i--)/i--;
    it is that you should not write such code, so as such, understanding it is not an issue - it is irrelevant (as well as undefined).

    If you wrote such code for me, I'd have to fire you.
  12. #7
  13. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,145
    Rep Power
    2222
    Originally Posted by anilkumartgsb
    ... , when I solve these questions theoretically I got some diff ans and when I run it on C compiler I got strange and surprising answers thats make me confused.
    What your programs actually do depends entirely on the code that the compiler generates. The language standard specifies kinds of behavior that that code must have when source code is translated, but it does not specify exactly how the code must generate that behavior. The standard specifies the end results, but not the specifics of the object code that is generated; the level of all object code would be far too detailed and virtually impossible, if not actually impossible, to specify.

    In addition, there are a number of things that are not defined. Such as changing and using the same variable multiple times within the same expression, which appears to be what you are trying to do (you have not told us yet what your code looks like). When you use undefined behavior, then the results are not guaranteed and will depend entirely on the code that your compiler just happens to have generated -- a different compiler would generate different object code that could very well display different behavior.

    The solution to undefined behavior is don't use it!

    Our main question is: why were you trying something like that in the first place? Did your teacher or textbook put you up to it? Did they give any reason for such lunacy as in "Was there any valid teaching point being made?"?

    If you need to understand the code that is generated, read my page, Evaluating (x + x * ++x). Some languages evaluate expressions on a stack (which is how you did it "theoretically") while others directly access and change the variable with each operation (which is undoubtedly what your program did).
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Posts
    16
    Rep Power
    0
    I was just solving diff diff question from this topic from by book, net etc. So I got some questions of this topic which are generating some diff answers then I expected.

    I was trying to solve this question.

    int a=3;
    int b = ++a + a++ + a-- + --a;

    and I think get my answer now too by our respective seniors here that in this question too a single variable is changing more than 1 time which is undefined as explained by all of you above.
    Thanks for all your responses. I definitely learnt a very imp concept of C language operators. Appreciate your help and looking forward to get my all concept related to this language correct.
  16. #9
  17. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,109
    Rep Power
    1802
    Originally Posted by anilkumartgsb
    I was trying to solve this question.

    int a=3;
    int b = ++a + a++ + a-- + --a;
    What you must really understand is that best, such code is at best interesting, but ultimately useless. Ask yourself; "when would I ever seriously write such code?"

    It speaks more to the quality (or rather lack thereof) of the resource you are using, that it might pose such an exercise without making it very clear that it is a counter example of what not to do, and serves no other useful purpose. The same resource should also if it presents such an exercise, include the information already given here as to why it is ill-advised.

    In the end however, I am of the opinion that such examples, even as warnings serve so real purpose. Unless as a novice you were exposed to such code, you would not likely independently think of or consider writing such code, so would never likely get yourself in to the kind of trouble that the code sees to illustrate.

    In the worst case, the code is presented as an example of how clever the writer thinks he is, and not as a counter-example at all! This thing you should remember about clever or apparently clever code:

    "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." - Brian Kerighan

    Write clear code you understand and which clearly exhibits your intent to others. Everything else gets short shrift around here as you have found. Had you searched the forum (as such questions come up frequently - especially at start of term), you'd have found similar responses and opinions. We never get tired of answering this one! :rolleyes:
    Last edited by clifford; January 11th, 2014 at 03:13 AM.
  18. #10
  19. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,607
    Rep Power
    4247
    While you're at it, stop using Turbo-C to learn how to program in C. The compiler is outdated and does certain things in a non-standard manner (to be fair, it was written a long time ago before some of those standards were established)
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  20. #11
  21. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Posts
    16
    Rep Power
    0
    Really I need to stop using Turbo - C! Well thats true it is bit oudated but hmm I find my self much used and comfortable on it. But yes change is the universal truth. Well thanks everyone for your responses, help and suggestion. Its been a great help and will be proven helpful for me later.
  22. #12
  23. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,109
    Rep Power
    1802
    Originally Posted by anilkumartgsb
    Really I need to stop using Turbo - C! Well thats true it is bit oudated
    That's not really the problem with it. The problem is that it generates 16 bit x86 real-mode code that runs in in virtualised MS-DOS environment and has no direct access to the operating system the code is running on. Worse than that, neither it nor the code it generates will run at all in Win64, so it is doomed.
    Last edited by clifford; January 15th, 2014 at 01:47 PM.
  24. #13
  25. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,607
    Rep Power
    4247
    Originally Posted by clifford
    That's not really the problem with it. The problem is that it generated 16 bit x86 real-mode code that runs in in virtualised MS-DOS environment and has no direct access to the operating system the code is running on. Worse than that, neither it nor the code it generates will run at all in Win64, so it is doomed.
    And because it runs on a virtualized MS-DOS environment, which has no memory protection, certain code which will not run in modern OSs will run just fine in Turbo C's environment. For instance:
    Code:
    #include <stdio.h>
    int main(void) {
        char *str = "hello world";
    
        printf("Before: %s\n", str);
        str[0] = 'H'; /* Change lower case h to upper case H */
        printf("After: %s\n", str);
    
        return 0;
    }
    The line that changes the lowercase 'h' to upper case 'H' should cause the program to segfault/core dump on most modern OSs, but will work fine in DOS, which has no memory protection. Therefore, people learning on Turbo-C have no idea why the program crashes on other environments and that the code is incorrect.

    As a side note, the declaration of *str should really be:
    Code:
    const char *str = "hello world";
    and any modern C compiler will catch any attempts to modify the contents of *str as an error. However, Turbo-C is old and doesn't understand the const keyword, so the programmer can't use it anyway.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  26. #14
  27. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Posts
    16
    Rep Power
    0
    Hmm...nice...I able to get new concepts from this discussion. Its great!! Thanks a lot.

IMN logo majestic logo threadwatch logo seochat tools logo