Thread: Incrementation in conditionals

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    140

    Incrementation in conditionals

    Hi guys

    My program does (or at least should do) the following: The user enters a sentence 19 characters long, or shorter. This string is saved in str.

    Code:
    #include <stdio.h>
    #include <conio.h>
    
    #define length 5
    
    void main()
    {
    	int i=0;
    	char str[length];
    	
    	
    	while(((i++) < length-1) && (str[i-1]=getche())!=13)
    	{
    	}
    	str[i-1]='\0';
    }
    My question is: When I use the incrementation-operator ++ in the condition of the while, then in the second condition, (str[i-1]=getche())!=13, is the original value of i used or is the incremented value used?

    Best,
    Niles.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Question 3.8
    && is a sequence point, so the ++ always happens before the right hand expression is evaluated (if it's evaluated at all).

    If you're confused, then just re-write the code so that it is clearer to you.
    Say
    Code:
    while(((i) < length-1) && (str[i]=getche())!=13) {
      i++;
    }
    Oh, and drop the void main, and use of conio.h
    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.

  3. #3
    Registered User
    Join Date
    Aug 2009
    Posts
    140
    Quote Originally Posted by Salem View Post
    Question 3.8
    && is a sequence point, so the ++ always happens before the right hand expression is evaluated (if it's evaluated at all).

    If you're confused, then just re-write the code so that it is clearer to you.
    Say
    Code:
    while(((i) < length-1) && (str[i]=getche())!=13) {
      i++;
    }
    Oh, and drop the void main, and use of conio.h
    Thanks. I will do as you said.

    Best,
    Niles.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. HEX-numbers after incrementation x in for-loop.
    By Jelte in forum C++ Programming
    Replies: 11
    Last Post: 08-05-2009, 10:36 AM
  2. conditionals
    By s_siouris in forum C Programming
    Replies: 3
    Last Post: 03-11-2008, 07:29 AM
  3. Type definitions within conditionals?
    By mushu in forum C++ Programming
    Replies: 4
    Last Post: 06-11-2006, 04:16 PM
  4. How to eliminate irrelevant conditionals?
    By cdave in forum C Programming
    Replies: 9
    Last Post: 12-10-2005, 04:39 PM