简体   繁体   中英

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().

This is my first real try at C programming. As an exercise, I figured I'd try using ncurses to get an intro screen with centered text. Nice and simple, ncurses did the trick since printf isn't really capable of it.

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. 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. 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 . If you code 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); ).

BTW your main has to return int . See C11 specification n1570 §5.1.2.2.1

Look also into some C reference site.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM