This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
sci4me's profile picture

Why does this Java code behave differently than this C code?

Started by sci4me, 15 December 2018 - 06:50 AM
sci4me #1
Posted 15 December 2018 - 07:50 AM
I have this C code:


#include <stdlib.h>
#include <stdio.h>

typedef unsigned char u8;

void m1();
void m2();

u8 *dp;

int main() {
	dp = (u8*) calloc(30000, sizeof(u8));

	dp += 1;
	*dp -= 1;
	while(*dp) {
		m1();
	}

	return 0;
}

void m1() {
	while(*dp) {
		m2();
	}
	dp += 1;
}

void m2() {
	dp -= 1;
	*dp += 1;

	dp += 3;
	*dp -= 1;

	dp -= 1;
	*dp -= 1;

	dp -= 1;
	*dp += 1;
}

It terminates, as expected.

I have this Java code:


public class test {
	public static void main(String[] args) {
		new test().run();
	}

	int[] tape = new int[30000];
	int dp = 0;

	void adjust(int n) {
		tape[dp] += n;
		if(tape[dp] < 0) tape[dp] += 255;
		if(tape[dp] > 255) tape[dp] -= 255;
	}

	void run() {
		dp += 1;
		adjust(-1);
		while(tape[dp] != 0) {
			m1();
		}
	}

	void m1() {
		while(tape[dp] != 0) {
			m2();
		}
		dp += 1;
	}

	void m2() {
		dp -= 1;
		adjust(1);

		dp += 3;
		adjust(-1);

		dp -= 1;
		adjust(-1);

		dp -= 1;
		adjust(1);
	}
}

It does not terminate.

Why do they behave differently?
Edited on 15 December 2018 - 07:21 AM
SquidDev #2
Posted 15 December 2018 - 09:46 AM
I'm fairly sure your adjust function is wrong. If the new value is 256, it will be replaced with 1, while you'd expect it to actually be 0. I think this'll work correctly:

if(tape[dp] < 0) tape[dp] += 256;
if(tape[dp] > 255) tape[dp] -= 256;
You might be able to get away with having a byte array instead, but can't say for sure.
Bomb Bloke #3
Posted 15 December 2018 - 12:10 PM
Java shouldn't complain about under / overflows. Depending on your use-case, though, the lack of an unsigned byte might be a problem.