Initializing variables in C

后端 未结 10 690
长情又很酷
长情又很酷 2020-12-02 12:21

I know that sometimes if you don\'t initialize an int, you will get a random number if you print the integer.

But initializing everything to zero seems

10条回答
  •  無奈伤痛
    2020-12-02 13:16

    In general, there's no need to initialize a variable, with 2 notable exceptions:

    1. You're declaring a pointer (and not assigning it immediately) - you should always set these to NULL as good style and defensive programming.
    2. If, when you declare the variable, you already know what value is going to be assigned to it. Further assignments use up more CPU cycles.

    Beyond that, it's about getting the variables into the right state that you want them in for the operation you're going to perform. If you're not going to be reading them before an operation changes their value (and the operation doesn't care what state it is in), there's no need to initialize them.

    Personally, I always like to initialize them anyway; if you forgot to assign it a value, and it's passed into a function by mistake (like a remaining buffer length) 0 is usually cleanly handled - 32532556 wouldn't be.

提交回复
热议问题