how to initialize the “min” variable properly?

后端 未结 4 461
野性不改
野性不改 2021-01-29 10:17

I have a small problem in my code for finding the minimum value from a series of numbers. When I initialize min = 0, the minimum value turns out as 0. But when I do

4条回答
  •  旧巷少年郎
    2021-01-29 10:29

    If you don't initialize a local variable, its value is indeterminate, and using that will lead to undefined behavior.

    What you should do is initialize it to a large value, just like you initialize max to a small value. Use INT_MAX from the header file.


    Also, if your variables can't be negative, you should probably use unsigned int, and initialize min to UINT_MAX.

提交回复
热议问题