函数2和3如何获取整数并在printf中浮动?这非常有趣,很想知道为什么吗?它与堆或堆栈有关吗?
#include <stdio.h>
#include <stdlib.h>
void function1(void){
int A = 50;
int B = 42;
float X = 3.1459;
float Y = 2.71828;
printf(“Function 1\n”);
printf(“%d+%d=%d\n”, A, B, A+B);
printf(“%f+%f=%f\n”, X, Y, X+Y);
}
void function2(void){
int v1, v2;
float cs, ua;
printf(“Function 2\n”);
printf(“v1+v2=%d\n”, v1+v2);
printf(“cs+ua=%f\n”, cs+ua);
}
void function3(void){
float cs, ua;
int v1, v2;
printf(“Function 3\n”);
printf(“v1+v2=%d\n”, v1+v2);
printf(“cs+ua=%f\n”, cs+ua);
}
Int main(void){
function1();
function2();
function3();
return 0;
}
输出:
Function 1
50+42=92
3.145900+2.718280=5.864180
Function 2
v1+v2=92
cs+ua=5.864180
Function 3
v1+v2=92
cs+ua=5.864180
这是未定义的行为。它们采用存储在存储器中的值。
When you write
int x
you ask the computer to get some memory to store anint
namedx
. If you don't assign a value to this variable, the value is the one that is in that memory location.它可能是由另一个程序或以前使用此内存位置的任何程序编写的。可能为0,因为从未使用过该内存位置,您不知道,该行为是未定义的(您无法定义该行为,您无法预测该值是什么)。
Also they are on the stack, the heap is for dynamic memory like when you use
malloc
.