[英]Why does my codeblock work in main() but not in its own function?
A block of code produces the expected results when placed directly within the body of main(), but not when split off into its own function and called from main().将代码块直接放置在 main() 的主体中时会产生预期的结果,但当拆分为自己的函数并从 main() 调用时则不会产生预期的结果。
This is my first real try at C programming.这是我第一次真正尝试 C 编程。 As an exercise, I figured I'd try using ncurses to get an intro screen with centered text.作为练习,我想我会尝试使用 ncurses 来获得带有居中文本的介绍屏幕。 Nice and simple, ncurses did the trick since printf isn't really capable of it.很好很简单,ncurses 做到了这一点,因为 printf 并不是真的有能力做到这一点。
So, I figure the next step would be to compartmentalize it within its own function as a first step to splitting it off into a separate .c file.因此,我认为下一步是将它划分为自己的功能,作为将其拆分为单独的 .c 文件的第一步。 I figure this would be a good way to practice splitting up code and referencing via header includes with the prototype in a .h file.我认为这将是练习拆分代码和通过头文件引用与 .h 文件中的原型的好方法。 Well, I never got that far.好吧,我从来没有走那么远。 The code block simply doesn't do anything when compiled and run as its own function.代码块在编译和作为自己的函数运行时根本不做任何事情。
By "doesn't do anything" I mean that when I run the compiled program, nothing appears on the screen and I simply get the prompt again. “不做任何事情”是指当我运行编译后的程序时,屏幕上什么也没有出现,我只是再次收到提示。
This is the version that produces the correct results:这是产生正确结果的版本:
#include <ncurses.h>
#include <string.h>
int main()
{
char mesg1[]="Space Tycoon";
char mesg3[]="Press Any Key To Continue";
int row,col;
initscr();
getmaxyx(stdscr,row,col);
mvprintw(row/2-1,(col-strlen(mesg1))/2,"%s",mesg1);
mvprintw(row/2+5,(col-strlen(mesg3))/2,"%s",mesg3);
refresh();
getch();
endwin();
return 0;
}
...and the version that does not: ...以及没有的版本:
#include <ncurses.h>
#include <string.h>
void intro();
void main()
{
void intro();
}
void intro()
{
char mesg1[]="Space Tycoon";
char mesg3[]="Press Any Key To Continue";
int row,col;
initscr();
getmaxyx(stdscr,row,col);
mvprintw(row/2-1,(col-strlen(mesg1))/2,"%s",mesg1);
mvprintw(row/2+5,(col-strlen(mesg3))/2,"%s",mesg3);
refresh();
getch();
endwin();
}
int main(){
intro(); // not void intro()
}
because you want to call the intro
function from your main
.因为您想从main
调用intro
函数。 If you code void intro();
如果你编码void intro();
you just are declaring (see C11 §6.7.6.3) inside main
that intro
function (and then you'll better give its signature, eg write void intro(void);
).您只是在main
中声明(参见 C11 §6.7.6.3)该intro
函数(然后您最好给出其签名,例如写void intro(void);
)。
BTW your main has to return int
.顺便说一句,您的 main 必须返回int
。 See C11 specification n1570 §5.1.2.2.1参见 C11 规范n1570 §5.1.2.2.1
Look also into some C reference site.还可以查看一些C 参考站点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.