Variable default values

匆匆过客 提交于 2019-12-20 08:07:19

问题


I'm confused about some basic theory in C programing:

  1. What are the default values for variables of different datatypes? Example: If I declare as follows what may be the result according to standard C manual which is documented by legend Dr. Dennis Ritchie?

    int x;
    printf("%d",x);
    

    I knows that some GCC compilers will print 0 and some print garbage values. It depends on compiler. Please give me the unique answer as per Dennis Ritchie C programing documentation.

    Same as above, please give me answers for float, char, double, string, array and pointers.

  2. If I declare and print pointer as follows:

    int *pt;
    printf("%d",pt);
    

    What will be printed on screen? I used MinGW GCCcompiler version 3.4.2, and in that I get a garbage value. Please help me in these confusions.

Thank you.


回答1:


The values of local (non-static) variables are indeterminate, i.e. you can't tell their values. Using an uninitialized non-static local variable leads to undefined behavior.

Global variables, and static local variables, are zero initialized. Unless initialized when declared of course.




回答2:


Default values:

  • Static local variables: 0
  • Static global variables: 0
  • Non-static global variables: 0
  • Non-static local variables: none

The address of a non-static local variable in a function depends on the state of the stack (the value of the SP register) at the point in execution when the function is called.

In other words, this address is not constant throughout the execution of the program, and setting a default value to such variable would essentially mean adding code to the program.

So the standard does not define a default value for non-static local variables, in order to allow the programmer to choose whether or not to add this extra piece of code.

All the other types of variables do have constant addresses in memory throughout the execution of the program, so setting them to a default value doesn't mean adding code to the program (their initial values are essentially part of the executable image).



来源:https://stackoverflow.com/questions/24583645/variable-default-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!