-2
private void delete(int[] nums, int i, int size) {
    while (i < size - 1) {
       //nums[i ++] = nums[i + 1];

       nums[i] = nums[i + 1];
       i++;
       
       System.out.println("i: "+i);

    }
    return;
}

I found that if replace the statement

nums[i] = nums[i + 1];
i++; 

with the comment part

nums[i ++] = nums[i + 1];

It throws OutOfIndex in java but performs well in C.

Selmo Jack
  • 67
  • 8

3 Answers3

2

It throws OutOfIndex in java but performs well in C.

C isn't Java. The C standard does not mandate anything what has to happen when you do prohibited things.

It only describes any constraint violation or violation against the "shall" mandating as "the behavior is undefined" or undefined behavior.

A C compiler doesn't detect such undefined behavior cases and just compiles the program. When you later run the program, you will never know what exactly will happen because the behavior is undefined.

So you can compile and run it, but the program is defective (at least if an implementation does not specify a behavior which shall happen in this case else).

Note that bad as it is, undefined behavior does not need to provide the wrong results, so be careful at coding in C.

1

In

nums[i ++] = nums[i + 1]

If the i++ happens before the nums[i + 1], i + 1 will be out of bounds on the last iteration. In that case, Java rightly causes an error, and C, because it doesn't do bound-checking, happily trusts the code you wrote.

That code is logically invalid. You're just unlucky that it didn't do anything obvious in your C program to cause suspicion.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
1

This program does not "perform well" in C.

In C, nums[i++] = nums[i + 1] is "Undefined Behavior" due to lack of sequence points. See sequence points in c This means the C program could do anything at all. You have no guarantees what the program will do when you run it.

In Java, the Language Specification defines exactly how nums[i++] = nums[i + 1] has to be evaluated: The left hand side of the assignment must be evaluated first, so i++ is evaluated first. The subsequent use of i on the right hand side must use the updated value of i.

Joni
  • 108,737
  • 14
  • 143
  • 193