Thread: Small error in C code segment

  1. #1
    Registered User
    Join Date
    Jun 2016
    Posts
    16

    Post Small error in C code segment

    The following code is supposed to set i to the first occurrence of a positive number in

    a[0], a[1], ... , a[n]

    or to n+1 if there are no positive numbers; however, the code is incorrect. I need help with what the problem is. Also, I need to write a corrected segment.

    Code:
    for ( i=0; a[i] <= 0 && i <= n; i++ )
          ;

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    For good measure, do "i <= n" before "a[i] <= 0". Otherwise, "i" may be "n+1", and "a[n+1]" is probably undefined behavior. There's no other flaw that I can see.
    Devoted my life to programming...

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    If there are n elements in the array, then the subscript test should be
    i < n;
    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. Is this C code segment correct?
    By SauceGod in forum C Programming
    Replies: 1
    Last Post: 07-13-2016, 04:18 PM
  2. Replies: 1
    Last Post: 08-28-2012, 06:11 AM
  3. segment error?
    By Butters007 in forum C Programming
    Replies: 6
    Last Post: 12-09-2006, 01:29 PM
  4. error in small code
    By asd010 in forum C Programming
    Replies: 15
    Last Post: 10-11-2006, 06:08 AM
  5. What does this code segment do?
    By Mr. Acclude in forum C++ Programming
    Replies: 2
    Last Post: 09-12-2005, 08:48 PM

Tags for this Thread