预测以下C程序的输出。
null
// PROGRAM 1 #include <stdio.h> #include <stdlib.h> int main( void ) { static int *p = ( int *) malloc ( sizeof (p)); *p = 10; printf ( "%d" , *p); } |
// PROGRAM 2 #include <stdio.h> #include <stdlib.h> int *p = ( int *) malloc ( sizeof (p)); int main( void ) { *p = 10; printf ( "%d" , *p); } |
以上两个程序都不是用C编译的。我们在C中得到以下编译器错误。
error: initializer element is not constant
在C语言中,静态变量和全局变量由编译器本身初始化。因此,它们必须用常量值初始化。
请注意,上述程序在C++中编译和运行良好,并产生10的输出。
作为练习,预测C和C++两种程序的输出。
#include <stdio.h> int fun( int x) { return (x+5); } int y = fun(20); int main() { printf ( "%d " , y); } |
本文由Shankar Shastri撰稿。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END