Page 1 of 1

Newbie Questions - Recursion - Resolved

Posted: Tue Mar 31, 2009 7:44 am
by dmcbeing
Hello every body this is my first post here.
First of all congratulations on your forum it has solved a lot of problems i had thus far.

I have started writing my kernel in c++.
I want to implement an ostream equivalent for a high res vga mode.
i have writen this :

Code: Select all

	cstream& operator<<(const int& val)
	{
		int temp = val;
		if(val < 10)
			(*this) << (char)(temp+48);
		else
		{
			
			(*this) << (temp/10);
			(*this) << (char)(temp+48);
		}
		return *this;
	}
I use this in main() as such:

Code: Select all

	int main()
	{
		cstream test;
		test << 1000;
		while(1)halt();
	}
Normally it should output 1000 , but instead i get 1XXX where XXX is garbage characters.
I cant really think something is wrong with the code so perhaps a stack corruption issue?
Does anyone have any clues?

Re: Newbie Questions - Recursion

Posted: Tue Mar 31, 2009 8:14 am
by ru2aqare

Code: Select all

	cstream& operator<<(const int& val)
	{
		int temp = val;
		if(val < 10)
			(*this) << (char)(temp+48);
		else
		{
			
			(*this) << (temp/10);
			(*this) << (char)(temp+48);
When exection gets to this line, temp is still larger then ten, so it's natural you get garbage output. You need to apply a modulus operator:

Code: Select all

			(*this) << (char)((temp % 10) + (int)'0'); // (int)'0' is more readable than +48, although functionally equivalent.
		}
		return *this;
	}

Re: Newbie Questions - Recursion

Posted: Tue Mar 31, 2009 8:20 am
by dmcbeing
Thanks ru2aqare, i should have seen that :S.