Jump to content

Beginning C programming

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
ady251981

ady251981

    Newbie

  • Members
  • Pip
  • 6 posts
Hi there, i'm totally new to this and have a problem already! lol Anyway i have just decided to start learning the language C, however after installing the compiler etc i wrote the very short program hello world! which consists of
#include <stdio.h>
main()
{
    printf("Hello World\n");
}

However after saving it as hello.c and then compiling it, i tried to run the program and you can see it comes up a blank screen with hello world written on it so it does work but it only stays for a split second and then disapears, can anyone tell me why this program wont display hello world untill i close it, i'm confused as to why it only runs momentarily, Thanks

Ady

Edited by Jaan, 01 September 2009 - 02:29 AM.
Please use code tags when you are posting your codes!


#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
That's because the program ends as soon as it finds the end line (which is supposed to have a return statement). It's a simple fix, do something akin to this:
#include <stdio.h>
int main()
{
    printf("Hello World!\n");
    getchar();
    return 0;
}
That'll keep the window up until you press enter.
Wow I changed my sig!

#3
ady251981

ady251981

    Newbie

  • Members
  • Pip
  • 6 posts
Thanks mate thats brilliant, i thought it was something simple and i have read up about the return 0; function i just did'nt know how to apply it and how it worked, thankyou for your answer anyway you have been a great help, cheers

Ady

#4
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts
Keep in mind that this "problem" is an effect of the environment from which the executable is run. If you were compiling and running from a command line, this "problem" would not appear, and you would not need the "solution". When running from many IDE's the program runs in a shell and when that program completes, the shell exits.

#5
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,715 posts
Also note that main() is always supposed to return an int. You can declare it one of two ways:

int main(void)
int main(int argc, char *argv[])

The second way is only necessary if your program takes command-line arguments.

Edited by dargueta, 28 August 2009 - 05:14 AM.
Code tags

sudo rm -rf /

#6
harryboss

harryboss

    Newbie

  • Members
  • Pip
  • 3 posts
Some IDE, like Visual Studio, has a debug option that automatically halt the program when it ends, to avoid the problem you are talking about. It is usually shift-f5 depending on the configured layout.

It is really a good thing not to include those "workarounds", if the program should execute well on a terminal-based system as well.