Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Getting started with C (not.cafe)
175 points by hdante on Dec 17, 2020 | hide | past | favorite | 103 comments


Introducing newbies to GTK is a great way to show them a lot of code they don't understand, will take a while to understand, and will break in non-obvious ways.


..and that uses non-standard concepts like GObject.

Win32 examples would have been peak hilarity.

More seriously, I see where the author is coming from, but even historically, GUI code has always been a massive pain in C.


Telling people that the default string type is LPTCSTR and the default integer type is HRESULT would be top trolling.


Right? What absolute beginners will learn about C from GObject? I bet most of them will learn that C is a weird language, and they also will learn that it is better not to learn about C again.


>Win32 examples would have been peak hilarity.

ExAmples


Being able to produce a GUI app may be more interesting to beginners than crunching some IO with basic console C program. Really, you don't need to understand GObject much to just use GTK+. Surface understanding suffices, and you can structure your program at first in such a way to not need to create custom GObject based classes/interfaces.

Beginners will probably be a bit lost, because the article doesn't go into any depth about event loop, retained mode GUI, GTK signals/handlers, nor does it link to GTK+ docs that would explain each part of the code, etc., etc.


I would be really interested in a course that actually holds true to the premise in the title here. I know my way around the JVM and python and started learning a little Rust on the side. However, I feel the need to at least dive my toes into C for a couple of weeks for completeness sake. Do you have a recommendation for something that is a little less than a book and a little more than learnCin10minutes?


It kind of depends on what you need out of C. The only real reasons left to use C in the wild are:

* Legacy code

* Embedded (including drivers, bare metal etc.)

* Portability, FFI, etc.

Performance used to be another major reason, but in $CURRENT_YEAR, if that's your goal, C++ and Rust are just as performant and there's very little reason not to opt into them.

The other major reason to learn C is that it's a great "hardcore introductory" language that will expose you to foundational concepts like pointers and memory management (it's really hard to understand what problems Rust is trying to solve if you're not familiar with malloc and free, for instance), but if you're already programming that's less of an issue.


I would still suggest that people learn C before attempting C++; while someone with C# or Java experience could probably do well in a "modern C++" codebase, as soon as they go off-piste into memory allocation and pointers they're in for surprises.

(Is there anyone who learns Rust who isn't already a proficient but frustrated C++ programmer?)


> Is there anyone who learns Rust who isn't already a proficient but frustrated C++ programmer?

Yes, I learnt Rust as a JavaScript/PHP/Python programmer who needed better performance for a project, and I'd thoroughly recommend it as a first low-level language. I found it much easier to learn than C++. There were a few new concepts to learn, but:

- There were far fewer than C++.

- The Rust Book provided a free and very approachable resource for learning them.

- The Rust compiler gave me immediate feedback if I was doing something wrong (no unexpected bugs in production)

- Most of my JS skills translated pretty straightforwardly

- /r/rust has a very helpful community which filled in any gaps that weren't covered elsewhere.

C is simple when you're working with toy examples, but as soon as you try to do anything moderately complex the complexity quickly jumps. e.g. If I wan't to use something as basic as a HashMap this is a trivial import in Rust or C++, but a non-trivial task in C. You either have to build/import a library (which is not that easy in C), or write one yourself! Same for string operations!


> (Is there anyone who learns Rust who isn't already a proficient but frustrated C++ programmer?)

We have a lot of people who come from ruby/python/js, and/or haskell/ocaml/scala. They find Rust an easier foray into systems languages than C++.

And even some C veterans who never got on board the C++ train.


Completely agree, that was part of the point I was making, for example, I doubt I would ever have understood RAII had I never seen malloc.

Parent was suggesting they are already a programmer, so I assumed they already had at least a grasp of how pointers and manual memory management work. If one happens to lack such knowledge, I agree learning C is an excellent first step.


I understood malloc very well long before RAII made sense to me.

I think what made RAII seem like a good idea was seeing a large C code base at a major company which had a consistent approach to cleanup and error handling. It's very possible to write good code that way, but it takes manual effort, discipline, consistency. At that point I understood that RAII was about letting the compiler handle what I was already doing in C.


I would recommend you to watch "CppCon 2015: Kate Gregory “Stop Teaching C"" https://www.youtube.com/watch?v=YnWhqhNdYyk


I learn Rust because I need a statically typed non-jvm alternative for backend and for me Go is lackluster in its expressiveness after coming from Scala.


Well for me one objective definitely would be to better my understanding of gnu tools, gcc etc.

But for the most part, yes it is about "foundational concepts". A lot of the time when you learn system level programming people will refer to certain quirks or terms from the C world.


If you're just looking for a cursory introduction to the underlying concepts, I agree with the other comments that K&R is what you are looking for. I'd add the caveat that due to the fact that C is a tiny language with a tiny standard library, most code you'll see in the wild uses custom concepts/libraries/object models on top of C. So for most practical purposes, there isn't really "C" as much as there is "unix programming C", or "embedded C", or whatever else have you, and all of them add a thick layer on top of the core language.


I had C as an introductory language and I didn’t perceive it as very hardcore, because we were doing the most basic things. Key is in my opinion, that you do projects aligned with your current programming skill level.

I have never used C professionally, so I never worked with a large, complex code base. But I think getting the foundational concepts from it as a first language has helped a lot along the way picking up and switching between languages.


Strong disagree. Unless you're using it as "C with classes", C++ is a nightmare hell language that you should only use if you're forced to by your environment. Stay far away.

C is a fine language, but it is from the 60s and 70s and feels like it. Rust is very nice, although poor for half-assed prototyping (which is actually maybe a good thing). Both are fine choices for systems-level programming.


I've been working on this which you might find of use:

https://github.com/glouw/ctl


That's interesting. Do I understand correctly though that the performance of CTL is mostly on a par with that of the STL?


Yes, I'd say at worst its 20% slower. The implementation is naive and readable (and therefor hackable). I did not have the time to implement all the heuristics that make STL as fast as it. The goal is hackability and ease of use (think text book function examples), while giving embedded engineers (or even desktop engineers with an aversion to C++) a chance to focus on getting their work done.

That, and lighting fast compile times, where programming feels like (oh, the heresy) a _drastically reduced C++_.


Not quite. I use C to interact with scientific libraries and to do some image processing. I would like to learn and use Rust but is still lacking in the scientific libraries department. I avoid C++ because it's a nightmare of complexity.


It's a fairly controversial pick amongst the C community, and it is a full book, but the first few chapters of 'Learn C the Hard Way' by Zed Shaw are (imo) a great resource to get started with the language, and also point you towards tools like Valgrind which you might not come across otherwise.


I have lecture notes for the intro programming course I taught a few years ago: https://a-nikolaev.github.io/cpp-spring-2015/

It is actually in C++, but the goal was to cover C features first as the foundation, before going into objects, strings, and similar more advanced concepts. (It still uses C++ I/O from the very beginning, since it's was a C++ course.)


Personally I think C isn’t useful to know topically. It really only became useful once I had a basic grasp on computer architecture, assembly language, and operating systems. Then suddenly its use made a lot more sense to me. If you’re not thinking about those things when writing C then you’re probably using it for the wrong reason, and there’s probably a better tool for the job.


CS50 online course uses C from “Week 1” and it’s set up for you in a controlled learning environment while you learn concepts.

If you have some programming experience you can probably jump straight to the Problem Sets.


Just read K&R for 10 minutes.


:-) I wish people would stop recommending this outdated book, along with a few other default goto books (say, the Dragon book).

Its super optimistic approach is more about the language K&R wanted C to be than the real thing.


The book is fine. It is way better to start off by sorting words from stdin with K&R than to follow a tutorial to do a GUI window.


I thought the book by K.N. King was a great introduction to (modern) C [0]. Easy to follow, nice questions at end of each chapter including a few challenges.

———

[0]: http://knking.com/books/c2/index.html


Maybe there aren't any good alternatives to "read this go to book as the first book on the topic". Prove me wrong. (Please)


If an absolute beginner were to use K&R as a start they'd be learning C from 35 or so years ago. It's well written, but not helpful as a reference. Even something as simple as how a function is organized has changed.

C Programming: a Modern Approach teaches C89 and C99, pointing out the differences in features when appropriate. Having used it myself this year, I found it much more helpful than K&R


If you start with the second edition (C89 / "ANSI C"), you'll discover that C has barely changed.


Yes, that's true. C Programming is largely a C89 book with small segments about C99.


I taught myself C using K&R when I was a teenager... back in 1991. The second edition was only a couple of years old.



Exactly.

It's a great read, even if you don't plan on programming in C.


The companion Programming in the UNIX Environment has some outdated details but a surprising amount of it still works.


Really. That's just cruel.

GTK is good, but the programming model is exactly that. Especially in C.

If bare C is giving beginners a knife to play with, GTK is telling them to put electrical wiring together and "have fun". Oh but the lamp socket looks like a banana and wires look like ropes and vice versa. Good luck!


The absolute beginner technical guide may be the most difficult kind of writing there is. You have to know what's already in the head of the absolute beginner. If it's garbage, you need to set that straight before anything else can happen.

You also have to know what's not in the head of an absolute beginner. Then you need to fill the gaps with background material. Not too much or your audience will tune out. Not too little or you'll lose your audience in a puff of confusion. There needs to be just enough instant gratification to keep the reader with you.

Many concepts you've mastered are tangled together in your head, and you'll realize this the minute you start trying to write about them. Before you started writing, you never noticed what a hairball of concepts you'd mastered, and if you don't expend some serious effort and energy unpacking it all, your absolute beginner guide will read more like a dissertation. You'll need to untangle each and every concept for the beginner audience. That means getting creative with how information is presented. With what information you reveal, and what information you simplify - but not too much. You should start thinking about ways to convey ideas graphically, which could excite you as much as it horrifies you. A good image can take as much effort as 2,000 edited words.

You start off thinking that it will be easy. And then you realize you've vastly underestimated how much material there will be to get where you wanted to be. If you haven't given up in complete frustration at the size of the undertaking in front of you, scale back your vision for the guide and repeat. It may take a few iterations before you know what you're doing.


> You also have to know what's not in the head of an absolute beginner. Then you need to fill the gaps with background material. Not too much or your audience will tune out. Not too little or you'll lose your audience in a puff of confusion. There needs to be just enough instant gratification to keep the reader with you.

Couldn't agree more.

I've spent probably a year incrementally revising a "getting started with Ruby" resource for a local software development program. [0]

I ended up with a 45 minute (!!!) walk-through of how to run a test file of string manipulation exercises. [1] I treasure each of the ~500 views it's got.

I spent probably 25 hours making, editing, and writing about that video.

I think this video is the single most impactful thing I've ever made, in the last 10 years I've spent making things. I treasure the DMs I've gotten in Slack, from students who have found the video extremely helpful, encouraging, etc.

[0]: https://github.com/turingschool/ruby-exercises [1]: https://www.youtube.com/watch?v=aeAkLxr5diE&feature=youtu.be


Yea, if I were writing something with the bold title "Absolute Beginner's Guide To..." I'd want to test it on my 8-year old who only knows how to launch the web browser and Minecraft. If she can use it successfully to cobble together a working Hello World program, then it's indeed an absolute beginner's guide.


Not only can she cobble it together - it has to be something that helps her feel a sense of pride, dignity, and understanding.

Some guides get someone to "the end", but they don't scaffold an understanding of the underlying principles, and the student feels even more confused at the end than at the beginning.

I always go to great lengths to show the mistakes that I make all the time, and to show how much of a given domain I don't know.

For example, in a Make an OSS contribution walk-through I did, I mention over and over how myself or the senior dev I was pairing with didn't understand something. [0] Most of the job of a modern software developer seems to be surfing across an ocean of complexity, avoiding everything except the _one specific issue_ we're working on.

To persons unfamiliar with the field, they might think that we actually understand everything to any degree of depth. They would be deeply mistaken.

[0]: https://intermediateruby.com/matt-swanson-jekyll-bug-p2


"Absolute beginners" does not mean there is no pre-requisite knowledge necessary, just no pre-requesite knowledge of C. If I took an "absolute beginners guide to calculus" it would be assumed or directly stated that the reader is expected to have some basic numeracy and literacy for the book.


Otherwise known as The Curse of Knowledge.

The reason so much documentation is garbage.


This is a very strange "getting started" guide to C, and I'm not sure who the intended audience could possibly be.

The tone at the start really does seem to be aimed at "absolute beginners" ("[...] programs must be written in a very strict way. Miss a comma and the program will stop working"), but then it quickly gets into the weeds without much explanation.

I'm trying to imagine an beginner reading this: The first thing we're told to do is "Installation", that makes sense. Then the first line says "The Apple provided C compiler is the LLVM clang compiler". But what's a compiler? How does that help me learn C? The tutorial hasn't even indicated that C is a compiled language, or what a compiler does at this point, and it doesn't elaborate on this throughout.

We go on to a hello world example, and we're told to type in some code ("Remember: programming languages are very strict, so type it exactly"), and then we're given an explanation of what it's doing: Great! I can't wait to learn what this means. But the explanation uses terms that a beginner would not be familiar with: The very first line of the explanation is "the first line loads the stdio.h function library, which provides the printf() function, used to write a message on the terminal". What's a function? What's a library? Obviously these things are trivial to anyone with programming experience, but for an absolute beginner, these terms don't yet have an intuitive meaning, and they're never fully explained in the article.

We compile that program (again, never being told what compilation is or why it's necessary), and then we're suddenly thrust into writing a GTK+ program. We haven't covered the absolute basics like types, pointers, etc, and yet we're given a huge chunk of (reasonably complex) code with no explanation, and just told to "read the code bottom to top" as an "additional hint".

I think a much better title for this would be "getting started with C tooling", but even then, the article does a very poor job of explaining why such tooling is even necessary.


Wrt "the first line loads the stdio.h function library, which provides the printf() function", you're right, "loading a library" is not clear and, what's worse, is actively misleading as actually we're just telling the compiler that there is a function somewhere called printf that will get "loaded" (linked) later on. I remember that this was one of the things that confused me most about C when I learned it.


We're really just telling the compiler to find a file called stdio.h and act as though its contents were included at that part in our program.

Whether the full function is there or linked later is a matter of implementation (some headers have full functions, typically trivial "inline" functions).

I can't remember what the standard says via the stdlib, but in general a library you load later on may not have all/some of those functions, but as long as you didn't use them you'll be fine (just as with a redundant forward declaration you yourself did).

And finally the whole "linking" part of C is mostly just a widespread convention, not something that the standard really dictates. See section 6.2.2 [1] for the brief words on it mainly to do with "static"/"extern". But the whole "compile" -> "link" (to some existing .so/.a) -> "program" is all implementation defined.

1. http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf


Yes, one of the confusing things for C newbies is the difference between "works this way on almost all implementations you are likely to encounter" and "actually part of the language". Both provide great opportunities for either the compiler or stackexchange answerers to make the newbie feel inadequate.


>that this was one of the things that confused me most about C when I learned it.

absolutely same, me too. and, there was no good websites / videos on the web back then.


Reminds me exactly of my attempt at C tutorial:

1. Aim for newbies. Vastly under estimate the amount of explaining that must entail

2. Peter out somewhere between the first and second real code example


Maybe they meant an absolute beginner to C and not programming in general.


I definitely agree that's possible, but then they go over what a terminal is and what the "ls" command means, and how case-sensitivity and using commas in the correct places are important when programming, which strike me as things which would be assumed knowledge if the audience were expected to have any programming experience.


Good point, although a lot of programmers now use an IDE for everything, so they may have no working knowledge of the command line (or a very limited knowledge).


I'm a beginner to C and not programming in general, but even I'd struggle to get some actionable knowledge out of skipping from "hello world" to "basic GTK application". This tells me basically nothing about how C works or how to write programs with it.


The immediate next step after "hello world" is GTK programming? This is only "getting started with C programming" if your idea of C programming is copying magic incantations into an editor. Which, sadly, is increasingly being treated as programming in the StackOverflow era.


I understand the motive to let readers get up and running quick, getting some graphical window instead of terminal black box, but if you think users want to avoid terminals and get to graphics, why spend a chunk of the article talking about it? Just when readers starting to like the terminal and the culture, the author goes "anyway, terminal sucks, let's get a graphic window! here's 100 lines of code you'll never understand"

I don't understand the bloat of introdocing gtk, meson and ninja, more deps means more code, more code means more bugs, more steps and more difficult to compile, I'm sure a lot of people will fail to compile this, which is very frustration for beginners who're not familiar with error messages. You might think meson and ninja makes it easy for building, but that's wrong, that might be true for engineers who build 1000 times a day, not for one off beginner situations like this. Abstractions is for people who understand why the abstraction is needed.


This strikes me as very out of touch with reality. You can't go directly from hello world to 100+ lines of 3rd-party code that uses pointers all over the place and just brush it off with "don't worry about the complexity".


The most critical prerequisite to being a good C developer is to really understand pointers on an intuitive level. The biggest block is that most people don't take the effort to develop mental fluidity. So when they see something like a dereference to a pointer of a pointer, or a cast from a pointer to an array, it interrupts flow while they consciously work out what's going on.


I'd say the most critical thing is to understand the relationship between ISO C standard, compiler implementations, and you, the programmer. Understanding that "seems to work" is not good strategy to deal with C, nor is trusting that things work in a sensible manner. Seeing how nasal demons might lurk at every corner. Distrust all advice and guidance that is not founded upon current C standard and/or compiler documentation. If you internalize that mode of thinking, then pointers will be just a minor detail in the end.


Personally, my major issue with pointers is the C syntax for them. While I understand why the & and * symbols were chosen for the task way back when, but it feels like a kludge. Smart pointers in C++ provide a more logical and consistent interface for using pointers.


I would be really interested in reading about why & and * were used as the symbols for pointers when C was originally conceived. Can you share a link or point me in the right direction for why that is? Please and thank you!


That escalated quickly, poor beginners :').


Exactly!

The author assumes the reader doesn't know what a terminal is, and goes from a "hello world" to a cross-platform graphical "hello world" using GTK-3 without explanation.

"Trust me, I don't have time to explain!"


You can teach anyone anything in ten minutes if you don't care about understanding or retention!


Step 1: write hello world in console.

Step 2: draw the rest of the fucking owl?!


Despite some (already mentioned) shortcomings, I like it: it provides a simplified "real life" big picture of the whole process with sample tools; a thing that (in my experience) every other "getting started" guide seems to miss (most of them just mentions what is a makefile).

I also like the overall format of the website and the radio feature is a nice touch. I'll visit it again in the future, out of curiosity.

A follow-up article may extend it with collaboration (git) or may delve in either Unix-like (e.g. with the GNU utils etc) or Windows, or both. But the author should first address the highlighted shortcomings...


It is funny if this was not intended as funny. An instance of "now draw the rest of the owl" meme. I can see the need to teach a bit of the surroundings of C, but it ended up having very little to do with C.


I think you nailed it: it's a "now draw the rest of the owl" gag. Very subtle.


Christ. What is this nonsense, and how did it get into the front page.

If by any chance you reading this and want to learn C, do obtain and read The C Programming Language 2nd edition instead.


I'd recommend An Introduction to C & GUI Programming by Simon Long[0] instead. It's much more beginner friendly and is very well written. Doesn't go super in depth but it's a quick intro book so it shouldn't. Plus it's a book and it's cheap/free;

[0] https://magpi.raspberrypi.org/books/c-gui-programming


C is the one language I think I can understand well enough to read, until I look at real code or see people complain about it.


I think this has merit not only for beginners to programming, but also for programmers who have never touched C. I like that it gets straight to business.

Good intro, and props to the author for introducing it on three major desktop platforms, using modern build tools.


Agreed, but not for beginners. I just about fall into the second category (I am a school teacher) - I have published (internally to my school) a couple of VB apps and written a lot of code in Python, but I have never touched C. I understand nearly all of the terminology and feel that I would be able to use this to learn more about C. Beginners (of whom I have taught many!) simply wouldn't be able to use it.


https://viewsourcecode.org/snaptoken/kilo/

This is the "getting started with coding" guide that I give to people who ask me about these kind of things. This is a defense mechanism - I tell them that I'll help them get started with a career in coding if they return me their completed text editor. So far nobody has, so maybe it's not the best beginner tutorial?

I still thought it was a great tutorial.


I have completed about 45 steps of this tutorial, totally love this!! Antirez is a total wizard. This is totally a no bullshit intro to C.


May be an unpopular opinion, but K&R 2nd edition is still the best beginner's tutorial for a fast start into the C for me. As the knowledge starts to build, better learning material and experience will also be consumed.

If I had read this lightning fast guide, I would be a bit lost. After displaying "Hello, world" on the terminal, do I really want to learn how to display "Hello, World" in a GTK window?


The writer intended this tutorial for absolute beginners without any experience in programming - which is, to be honest, totally bonkers! It's not a bad guide for someone trying to learn C as their second/third language though, it teaches you how to prepare a build environment to use third-party libraries in C, which is seldomly documented this clearly compared to other random articles on the Internet.


I think a lot of beginners would be put off by the verbosity of this.


Learned a bit of C, not convinced it had any real benefit besides learning about pointers kinda drives things home for you about passing stuff around by values or reference if you are a self-taught Java / C# developer.

What set me on this path to enlightenement was an e-mail article from Dan Abramov (https://github.com/HackYourFutureBelgium/just-javascript/tre...) - here's an excerpt:

"We will learn about the JavaScript world for what it is — without thinking about how it’s implemented. This is similar to how physicists can talk about properties of stars without answering the question whether the physical world is real. It doesn’t matter! We can still describe it on its own terms.

Our mental model does not attempt to answer questions like “How is a value represented in the computer memory?” The answer changes all the time! In fact, the answer to this question changes even while your program is running. If you heard of a simple explanation about how JavaScript “really” represents numbers, strings, or objects in memory, it is most likely wrong.

To me, each string is a value. Not a “pointer” or a “memory address” — but a value. In my universe, a value is good enough. Don’t allow “memory cells” and other low-level metaphors to distract you from building an accurate high-level mental model of JavaScript. It’s turtles all the way down anyway!

If you’re coming from a lower-level language, set aside your intuitions about “passing by reference”, “allocating on stack”, “copying on write”, and so on. These models of how a computer works often make it harder to be confident what can or cannot happen in a JavaScript program. We’ll look at some of the lower level details, but only where it really matters. They can serve as an addition to our mental model, rather than its foundation.

...

As for these strange visions, I don’t pay as much thought to them anymore. I have wires to point, questions to ask, and functions to call. I better get to it! The stars are bright when I look at them.

Are they still there when I blink? I shrug.


Very interesting article and as someone who’s a beginner in C you definitely did a great job explaining


Totally unrelated, but I'm surprised to see pacman being used on Windows. Really? Windows, btw?


pacman is a great cross-platform package manager, it's being used in MSYS2 and a few other places besides Arch


I use pacman when working with windows. whats wrong with that?


Nothing! I was just caught off guard.


The C programming language 2nd Edition from K&R is much better than this.

Just compile all code with "cc -o file file.c", except for the math library, where you need to add "-lm".

Use whatever editor you like. Nano, nvi, emacs, whatever.


The article uses nano throughout. Is nano a popularly used editor? I have not seen anyone around using nano. I see vim, atom, sublime, vs code but never nano. Just curious if nano is popular.

If nano is popular what are its pros and cons?


Nano is the easiest-to-use terminal-based editor that you're likely to find on a Unix system by default. All the important key commands are listed at the bottom of the screen and everything! It's a great editor to recommend in beginner tutorials since it requires very little setup or learning to use, but if you're already happy with a different one there's probably no reason to switch.


I was kind of surprised that they had installation steps for it, to be honest–macOS certainly ships with it.


I use it on a daily basis. It's simple, fast and has syntax highlighting. And it's still actively developed[0] (latest release: 2020 December 2 - GNU nano 5.4 "Terre des hommes")

[0] https://www.nano-editor.org/news.php


I've found nano really easy to pick up for quick introductions to editing files via a terminal.

Nano seems to have a shallow learning curve for new users in comparison to vi, vim emacs as it works similar to other simple text processors.

It isn't as powerful as other editors and can't be configured as much but for some, especially beginners, that's a benefit.


to be honest nano is the best thing in this article, everything else is just disaster, nano is at least light weight and functional (imagine using an IDE for this)


Personally it's simple and all the important shortcuts are displayed on the screen.

If I ssh into a machine to change a config value I prefer it to vim/vi.

I'm not going to write anything using it, but for quick edits it's perfect.


Can AI generate a better tutorial?

To test my theory, I asked the OpenAI API to complete the following sentence:

    This tutorial will guide you through writing the "Hello World" program in the C programming language.

And here's the result:

    This tutorial will guide you through writing the "Hello World" program in the C programming language.
    
    Hello World Program Structure

    The "Hello World" program is a very simple program. It consists of two parts: the main function and the printf function. The main function is the first function called when your program starts running. It is responsible for starting all other functions and initializing everything that needs to be initialized before your program starts doing anything useful. The printf function is responsible for printing text to the screen. In this case, it prints "Hello World!" to the screen.
    
    The main Function
    
    The main function must have one argument which is an integer that represents how many arguments were passed into it from the command line (if any). The following code shows a simple main function:

    #include <stdio.h>
    int main(int argc, char *argv[]) {
        printf("Hello World!n");
        return 0;
    }

    This code will print "Hello World!" to the screen when executed.

    Let's go over each line of this code:

    #include <stdio.h>
    This line tells the compiler to include stdio.h in our program so we can use its functions (like printf ).

    int main(int argc, char *argv[])
    This declares a new variable called main . It has two arguments: argc and argv . These are special variables that are used by C programs to pass information into their functions from their command line arguments (if any). We'll talk more about them later on in this tutorial when we cover how to use command line arguments with your programs. For now, just know that they're there so we can use them later on if we need them! ;-)

    printf("Hello World!n");
    This line calls our friend printf . It tells it to print "Hello World!" followed by a newline character (the n at the end).

    return 0;
    This line returns 0 back into our calling environment (in this case, it's our shell). If you don't know what returning values means or why you would want to do it, don't worry about it for now; just know that every C program must return a value back into its calling environment when it finishes running (we'll talk more about this later on in this tutorial).
Pretty good, eh? (I just formatted the text for clarity.)


I want to believe this is real.


Is the AI messing up the newline? or is that just HN formatting

quite impressive. now ask it to solve the K&R exercises ;)


One of my biggest bugbears on C / C++ programming is return 0; I wish people would #include <stdlib.h> /<cstdlib> and use EXIT_SUCCESS / EXIT_FAILURE just to make the code more obvious for the beginner on what the intent is. :-) To quote the "zen of python" "Explicit is better than implicit" we know what "SUCCESS" or "FAILURE" is! And we can use enums for other exit values.


There should only be one way to succeed. Returning 0 for success makes complete sense. You can add layers of macros or enums to sugar coat this but retuning 0 for the success case makes complete sense


Yes, but if you use "magic constants" in your code, you will flunk code review in any halfway competent shop.

Always use the constant symbols.


Flunked for returning 0 from main() in C? Not sure that's a competent shop.


Have you seen any syscall implementation?


Returning either EXIT_SUCCESS or 0 is a valid way to terminate the program with an implementation-defined exit code appropriate for your platform.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: