Problem with for loop

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
asd
Posts: 3
Joined: Sat Jan 28, 2012 11:42 am

Problem with for loop

Post by asd »

Hi all, I'm new in this forum and since I've found solutions for every my problems in os development I decided to join the comunity.

Now, my problem is with the for loop in same cases:

I wrote (reading some tutorials) the code for the irq interrupts succesfully. The keyboard interrupt put in a global variable the ascii code for the key it has just read. Implementing the getch function I wrote a for loop like "for (; key == 0; ) ;" but is does not work. I changed it with "for(; key == 0; ) putchar('\0');". Ridiculous but it works. In "puthcar" I put some "if" and a "move_cursor" function wich uses "outb".
Another case is when I worked with the CPU clock and I tried to calculate time spending during some instructions. The istructions were some "for (i = 0; i < 1000000; i++) ;" and the "for" exit immediately. I put a "printf("%d\n", i);" in the for and now it works.

My question is why I did have to do that? I really do not know a rational reply...
Has anyone had the same problem?

(Sorry for my probably bad english, I'm italian :))
asd
Posts: 3
Joined: Sat Jan 28, 2012 11:42 am

Re: Problem with for loop

Post by asd »

Solved.
I put a "-O3" in my gcc flags thinking it could be useful, all works without it. I probably have to read better the man page.

Hoping this post can help others, enjoy your weekend :)
User avatar
AJ
Member
Member
Posts: 2646
Joined: Sun Oct 22, 2006 7:01 am
Location: Devon, UK
Contact:

Re: Problem with for loop

Post by AJ »

Hi,

In your first example, is 'key' declared volatile? If not, the compiler will see that nothing is changing the value of key and will do one of two things (I'm not an expert in compiler optimisation, but one of the following seems logical):

1. See that nothing in the loop modifies 'key', so cache the value and go in to an infinite loop.
2. See that the loop does absolutely nothing (no memory writes) and so optimise the loop out completely.

Cheers,
Adam
asd
Posts: 3
Joined: Sat Jan 28, 2012 11:42 am

Re: Problem with for loop

Post by asd »

No, just a char.
I'll try as soon as possible but in the first example you're right: it went in to an infinite loop.
However I can't understand the second example: in the for I modified the variable (everything was local in the main) so the compiler had to see that something was going on.

I'll document on the web.
Anyway, thank you for your help and your time :)
Post Reply