C Language Basics
Learn the C toolchain and core syntax to express algorithms precisely and efficiently.
Content
Program Structure and main
Versions:
Watch & Learn
AI-discovered learning video
Sign in to watch the learning video for this topic.
Program Structure and main in C — CS50 Style
"If functions are tiny machines,
mainis the red button at the control panel. Press it, and the whole program wakes up."
You're already familiar with core mental models from Computational Thinking — decomposition, abstraction, and algorithms. Now we move from the mental model to the physical stage: how a C program is laid out and how the operating system finds the place to start running it. This lesson builds on what you learned about compilers, linkers, and Make: the compiler translates your C into object code, the linker stitches pieces together, and main is the entry point the OS calls when it executes your program.
What is program structure in C? (Quick map)
Think of a C program like a play:
- Headers (the program's wardrobe and props):
#include <stdio.h>etc. - Global declarations (the stage scenery): global variables, constants, function prototypes.
- Functions (actors): reusable blocks of behavior.
main(the protagonist): the function the runtime calls first.
A minimal C file:
#include <stdio.h>
int main(void)
{
printf("Hello, world!\n");
return 0;
}
#include <stdio.h>gives usprintf's declaration. Without it, the compiler may warn or assume incorrectly. (Remember our previous chat about the compiler's role?)int main(void)declaresmainreturns anintand takes no parameters.
Why main matters
- Entry point: The OS looks for
main(or a runtime wrapper that callsmain) to begin execution. - Contract with the OS: The integer return value of
mainis the program's status code — 0 means success, non-zero generally means failure. - Interface for input:
maincan accept command-line arguments, letting the OS or user pass data into your program.
Design thinking: main as top-level algorithm
In computational thinking terms, write main as the high-level algorithm: set up, call functions that do the heavy lifting, handle results, and exit. Keep main readable — it should read like a short story about what the program does.
Valid main signatures and what they mean
| Signature | What it means | Use-case / notes |
|---|---|---|
int main(void) |
No command-line args | Simple programs; recommended over void main() |
int main(int argc, char *argv[]) |
Receives argument count and array of strings | Programs that read command-line arguments (CS50 argv parsing) |
int main(int argc, char **argv) |
Same as above, different syntax | Equivalent; pointer-to-pointer form |
Avoid void main(). It may work on some compilers, but it's not standard-conforming: main should return int so the program can report success/failure to the OS.
Example with arguments:
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Program name: %s\n", argv[0]);
if (argc > 1)
printf("First argument: %s\n", argv[1]);
return 0;
}
argc(argument count) is at least 1:argv[0]is the program name or path.argvis an array of C strings (null-terminatedchar*).
return vs exit vs implicit return
return 0;at the end ofmainsignals success.return 1;(or other nonzero) signals an error; conventions vary which nonzero value means what.exit(status);from<stdlib.h>terminates immediately and performs cleanup. Use it if you need to exit from deep inside a helper function.- In C99 and later, falling off the end of
mainis equivalent toreturn 0;— but being explicit is clearer.
Where compilers, linkers, and Make fit in (quick recap and pointers)
- You write
.cfiles that the compiler (e.g.,clangin CS50) turns into object files (.o). - The linker combines object files and libraries into an executable and ensures there's a single
mainfor the entry point. - Make automates these steps and avoids recompiling unchanged files.
Tip: If the linker complains about an undefined reference to main, probably you forgot main or mis-typed its signature. If it reports multiple definitions, you accidentally defined main twice or linked two files that both define it.
Small checklist before you run your program
- Did you
#includeheaders for functions you use? (e.g.,<stdio.h>,<stdlib.h>) - Is
maindeclared asint? (Notvoid.) - If you use
argv, do you respectargcto avoid out-of-bounds access? - Does your program return meaningful status codes so scripts and users can tell success from failure?
Ethics, collaboration, and code provenance (CS50-style reminder)
You can (and will) read other students' code and online examples — that’s how learning happens. But remember our Computational Thinking modules on academic honesty and ethics:
- Don't copy someone else's solution and submit it as your own. That breaks the contract with CS50 and with yourself.
- If you adapt an idea or a snippet, document and attribute it in comments.
- Learning to structure
mainand programs is part of your skill-building. Use others as inspiration, not as a shortcut past learning.
Quick examples & small anti-patterns
Bad: accessing argv[1] without checking argc — crash waiting to happen.
Good: keep main lean. Push logic into functions you can test separately.
int main(int argc, char *argv[])
{
if (argc < 2)
{
fprintf(stderr, "Usage: %s input-file\n", argv[0]);
return 1;
}
return process_file(argv[1]); // clear and testable
}
Key takeaways (so you can say them out loud like a networked brain)
mainis the official entry point; useint main(...)and return status codes.- Keep
mainhigh-level: set up, delegate to functions, tear down. - Command-line args live in
argc/argv— always checkargcbefore usingargv[i]. - Headers matter: include the right ones so the compiler knows what you're calling.
- Be honest: credit sources, don't copy solutions, and use others' code to learn, not to cheat.
"A clear
mainis like a good table of contents: it tells readers (and your future self) what the program does without making them read every paragraph."
Now go write a main so crisp your future debugger says, "I didn't even need to wake up for that one."
Happy coding. Make, compile, run, repeat — and keep the mental models close.
Comments (0)
Please sign in to leave a comment.
No comments yet. Be the first to comment!