Corning Community College
CSCS1730 UNIX/Linux Fundamentals
Assignments, Documents, Information, and Projects
C code to display “Hello, World!” followed by a newline, to STDOUT:
/* hello.c - a UNIX-style "Hello, World!" program * * To compile: gcc -o hello hello.c * To execute: ./hello */ #include <stdio.h> // referencing the C library; stdio is the standard I/O operations int main() // everything needs a starting point, in C, that is a function called main() { // when you have a group of statements, wrap them in a code block using the curly braces int i = 0; // as C is lower level, variables need types assigned and declarations. char *msg = "Hello, World!\n"; // A "*" denotes a memory variable, aka pointer while (*(msg+i) != '\0') // keep looping while the currently read character from msg is not '\0' fputc(*(msg+i++), stdout); // display currently read character to STDOUT return (0); // all done, notify the system all went according to plan } // close code block
Memory variables are merely variables whose purpose is to contain a memory address. If we want to see what is inside the memory address contained within our memory variable, we have to dereference it, with the * operator. Note our addition of i to message within the parenthesis… we are numerically adding numbers to the address, BEFORE we dereference it. This is known as pointer arithmetic, and can be used to enable rather slick solutions to problems.
The key takeaway here is that, even if you don't know C enough to write a program on your own, you should be able to identify organizational structures, and even tweak minor things to enable the program to perform in a more optimal way. There are manual pages that can be referenced for many STDIO C functions (including fputc), and I would highly recommend perusing some of them to get a better handle on what is going on.