A bug caused by a local variable which just named "a" in Keil C51V961

My keil is the latest version C51V961.

The code is very simple:

#include "reg52.h"
#include "stdio.h"
#include "intrins.h"

void uart_init()
{
	SCON = 0x52;
	TMOD = 0x20;
	TH1  = 0xfd;
	TL1  = 0xfd;
 	TR1  = 1;
}

void main()
{	
	unsigned int a=17; // note: the name "a" caused the bug
	unsigned int b;
	uart_init();
	for(b=2;b<=a-1;b++)
	{
		if(a%b==0)
			break;
	}
	if(b<a)
		printf("%d is not a prime number",a);
	else
		printf("%d is a prime number",a);
	while(1);
}

The steps to repeat the bug:

1. create a at89s52 project.

2. copy and paste the above code to the main.c file of the project.

3. compile the project, and click the "start/stop debug session" button to launch the debug session, then click the "step over" button, watch the value of local variable "a" and "b", everything is OK. 

4. stop the debug session.

5. click the "start/stop debug session" button again, then click the "step over" button, watch the value of local variable "a" and "b", then the values change as unexpected.

Conclusion:
1. When the name of the local variable is “a”, only the result of the first compilation is correct. The second and subsequent compilation results are incorrect.
2. If I move variables "a" and "b" outside the main() function to become global variables, then everything will OK and there will be no more bugs.

Please observe the GIF animation:

(P.S. Please "save as" this gif if it is small in the webpage)

And the project I used:

test2.zip

Parents Reply Children