c语言函数内定义函数


在同事的程序里面发现了一个小函数:

   
  #include <stdio.h>
  
void test1(void)
{
void test2(void)
{
printf("test2\n");
}
test2();
printf("test1\n");
}

int main(void)
{
test1();
return 0;
}

其中test2只能在test1里面被调用,如果在main里面调用test1的话,会打印出来test1和test2,自己感觉这个语法怪怪的,以前只在python/ruby见过相似的用法,不知道这个用法是c语言的标准语法还是gcc(用gcc 4.6.3编译)的语法扩展?
另外这种用法在实际中有哪些用途?

c 编程语言

【初音ミク】 11 years, 9 months ago

tiger@ubuntu:/mnt/hgfs/figure-it/DailyTest$ cat fun2.c
void test1(void)
{
void test2(void)
{
printf("test2\n");
}
printf("test1\n");
}

int main(void)
{
test1();
return 0;
}
tiger@ubuntu:/mnt/hgfs/figure-it/DailyTest$ gcc -o fun2 fun2.c
fun2.c: In function ‘test2’:
fun2.c:5: warning: incompatible implicit declaration of built-in function ‘printf’
fun2.c: In function ‘test1’:
fun2.c:7: warning: incompatible implicit declaration of built-in function ‘printf’
tiger@ubuntu:/mnt/hgfs/figure-it/DailyTest$ ./fun2
test1
tiger@ubuntu:/mnt/hgfs/figure-it/DailyTest$ gcc -v
Using built-in specs.
Target: i486-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.4.3-4ubuntu5.1' --with-bugurl=file:///usr/share/doc/gcc-4.4/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --enable-shared --enable-multiarch --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.4 --program-suffix=-4.4 --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-plugin --enable-objc-gc --enable-targets=all --disable-werror --with-arch-32=i486 --with-tune=generic --enable-checking=release --build=i486-linux-gnu --host=i486-linux-gnu --target=i486-linux-gnu
Thread model: posix
gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5.1)

没有遇到你说的这种情况,上面试我在虚拟机上执行的结果。

有没有这个头文件,只是编译报警问题,基本不影响结果。添加头文件后,结果相同,只是没有编译警告而已。当然,有些警告是不能忽略的。
tiger@ubuntu:/mnt/hgfs/figure-it/DailyTest$ cat fun2.c
#include <stdio.h>

void test1(void)
{
void test2(void)
{
printf("test2\n");
}
printf("test1\n");
}

int main(void)
{
test1();
return 0;
}
tiger@ubuntu:/mnt/hgfs/figure-it/DailyTest$ gcc -o fun2 fun2.c
tiger@ubuntu:/mnt/hgfs/figure-it/DailyTest$ ./fun2
test1

-----这是我看到问题后自己写的代码,效果相同:
tiger@ubuntu:/mnt/hgfs/figure-it/DailyTest$ cat fun.c
#include <stdio.h>

void test1()
{
void test2()
{
printf("222\n");
}
printf("111\n");
}

int main(int argc, char** argv)
{
test1();
return 0;
}

tiger@ubuntu:/mnt/hgfs/figure-it/DailyTest$ gcc -o fun fun.c
tiger@ubuntu:/mnt/hgfs/figure-it/DailyTest$ ./fun
111
tiger@ubuntu:/mnt/hgfs/figure-it/DailyTest$

弹幕下D杀手 answered 11 years, 9 months ago

Your Answer