Jump to content




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


2 replies to this topic

#1 sci4me

  • Members
  • 225 posts
  • LocationEarth

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 by sci4me, 15 December 2018 - 08:21 AM.


#2 SquidDev

    Frickin' laser beams | Resident Necromancer

  • Members
  • 1,427 posts
  • LocationDoes anyone put something serious here?

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.

#3 Bomb Bloke

    Hobbyist Coder

  • Moderators
  • 7,099 posts
  • LocationTasmania (AU)

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.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users