Hello, my name is Duck.
Recently I have been working hard on software training.
With CPUs now being included in FPGAs, the need for software is becoming more and more important.
In this article, I will solve a problem I encountered during training in C language, which is often used in embedded systems.
Initial Value Problem
In the past, I read in an article by Ume-Onigiri-senpai that HDL requires the input of initial values.
In fact, this initial value problem also exists in C language, and I was troubled by it many times.
In Ume-Onigiri's article, the initial value problem was a simulation problem.
However, in the case of C language, it can be a big problem that affects the actual operation.
Now, what happens when initial values are not set in C language?
For example, consider a program that displays numbers from 0 to 9 on the console.
Let's use a loop statement to display them.
Loop statements mainly include for and while statements.
Here is the same program written with for and while statements.
test1 code ( for ) test2 code ( while )
I thought I got it right, so I tried executing each of them.
test1 output result test2 output result
What?
The for statement outputs correctly, but the while statement does not display anything.
???
What went wrong?
Investigating the cause
This program is very simple.
The only thing that seems to be a problem is the variable i.
For debugging, we added the following printf( ) to check the value of i.
test3 Code
test3 output result
I got some weird numbers.
Huh? I don't remember putting this kind of number in, and then I realized that I thought ・・・・.
I didn't assign any value to i.
Problem solved!
So I decided to assign 0 to i at the beginning.
test4 Code
Let's run it.
test4 Output Result
Now the output is correct.
It seems that the variable i had an undefined value because no initial value was entered.
Since the condition for this while loop is i < 10, if i is greater than 10 at the beginning, the loop will not start.
Therefore, it seems to have terminated without entering the while loop.
Nothing is displayed.
We now know that the initial value input is very important.
Conclusion
It is easy to forget to enter an initial value in a for loop, but it is easy to forget to do so in a while loop.
If you do not enter the initial value, you do not know what value the variable will have.
This can cause bugs, so I made a mental note to be careful.
New Engineer's Blush Blog Article List