Skip to main content

Learning to Code III: Hello World

In my earlier posts (I, II, and Intro), I explained that I'll be using Xcode to learn Objective-C and the Cocoa Frameworks to learn about programming OS X and iOS applications. If you look back at those posts, you will find how to create a new command line application in either C or Objective-C.

This blog entry compares "pure C" to the C code I'll be using within an Objective-C file. Because Objective-C is a superset of C, you can use any valid C programming code in an Objective-C file. After this blog post, I'm going to be doing all coding within Objective-C projects, for simplicity among other reasons.

Hello, C Programming

Begin by creating a new "Command Line Tool" project in C. Apple's Xcode handily creates the code to output "Hello World!" to the command line. Run the code and you'll see the results in the "debug area" of the Xcode window. Ah, for the old days when aspiring young coders had to type the "Hello World!" program with one hand while holding a book or magazine flat with the other. (Yes, that's how I learned to program: I typed in the programs that appeared in various magazines.)

Here is the complete C version of "Hello World!" created by Xcode:
//
// main.c
// Hello World C
//
// Created by Scott Wyatt on 2013-04-04.
// Copyright (c) 2013 Tameri Publications. All rights reserved.
//

#include

int main(int argc, const char * argv[])
{

// insert code here...
printf("Hello, World!\n");
return 0;
}

Comments

The first seven lines are comments. They don't do anything, at least not as far as the compiler is concerned. Comments are essential to good programming, though. You include comments in code so other programmers (and you) can later recognize what the code is meant to be doing. Most programmers also use comments to record when a change was made to code and by whom. Single-line comments in C begin with //. The Xcode template could use multi-line comments, which begin with /* and end with */. You'll see multi-line comments in some examples I tryout later in this series.

I'm going to write a single post on comments and code formatting, because documenting your code is an essential skill for programmers.

In the comments above, Xcode has included notes on the name of the source code file (main.c), the program's name, and some copyright information. The comments were generated based on the data entered when creating the new project. The automation saves a little time.

Directives

After the comments is a "compiler directive." The directive in the template example is possibly the most common C compiler directive. It directs the compiler to include the standard input/output library ("header") source code when compiling this application. The "stdio.h" file includes the source code for many important "functions" programs need. Not only will your programs include standard libraries, but also code you write to reuse as a developer.

Don't worry about some of the terminology for now. I'll be explaining functions, libraries, headers, and more as the programs in this series get more complex.

Directives begin with a hashtag (# "pound" symbol) and do not end with a semicolon. That's important because statements in C usually end with semicolons.

The main() Function

I've heard C code described as a web of functions, all leading from and to main(). If you want to program in C, you need to understand the format of functions.

main() is a special function. Every C (and Objective-C, C++, C#, et al) program begins at main() and most also end at main(). I won't argue that its role as the starting point for execution is all that makes main() special, but that is the big difference between main() and all other functions. In terms of syntax and coding, main() is like other functions.

I'm going to detail functions in a dedicated post, too. For now, I want to explain the most basic features of the main() function created by Xcode. Look back to the code above. In plain English, the main() function in the template means the following:
  1. main() is a function that returns an integer value.
  2. If the user executing this program has included "command line arguments" after the application's name, please store those arguments for later processing.
  3. Execute the code within the curly-braces.
  4. Return the integer value "0" via main() when finished.
Most functions return values. Even functions that we seldom assign to variables or test, can and do return values. You need to tell the compiler what type of value or values will be returned by a function. In our example code, int main(…) tells the compiler that when main() is finished, it will return with an integer value.

What if you don't care about a return value? Many simple main() functions are written in the format:
void main(void) {…}
or
int main(void) {…}
I really, really dislike both of these examples — yet they appear in many programming books. I'll explain more in my post on functions, but for now you should know that I believe all functions should return something. I can use return values to let other functions know when there has been a problem. For example, I could use "0" to mean everything went well and return a number to report an unexpected situation. Error codes, once familiar to DOS users, are return codes.

Many command line programs are followed by user input. A reminder, Apple calls these programs "command line tools" in Xcode. User input included on the command line are called arguments, "parameters", or "switches" depending on their purposes.

DOS and Unix/Linux users know the command line format well:
dir c:\*.* /p /w

ls -l
The directory (dir) and list directory (ls) commands are programs. They accept parameters and switches, which tell these utility programs which files and directories to list, and how to format that list. If something goes wrong, the commands return an error code, which leads to an error message. This is how most command line programs work.

How does C know you might (or might not) include parameters and switches?
int main(int argc, const char * argv[])
The parameters arc and argv contain the argument count and an array of character strings with the user input. Of course argc is an integer — you can't enter a fraction of an input argument! Again, many of these concepts will be explored later. The "Hello World!" program doesn't do anything with arguments, anyway. Including the argument variables in main() does prevent an error if the user includes any (meaningless) arguments.

For now, leave the argument variables in main() when entering example programs.

The statements defining a function appear within two curly braces ( { } ). These braces mark the beginning and end of the function. Most programming editors, including Xcode, will let you know if a function is "unbalanced" because you forgot to include a curly brace somewhere.

Displaying Text

In classic old C, the printf() function sends output to the screen. Here we can see that most functions and statements within a C program end with the semicolon. I'm not going to explain printf() in this sample. I bet you can guess how it works. Maybe the "\n" is also easy to guess?
printf("Hello, World!\n");

Ending the Program

The main() function ends with a return {value} statement. I've already mentioned the importance of return values. You can omit the return statement, but I like to include it whenever possible.
return 0;
Technically, the end of main() is the closing curly brace. All function definitions end with their last brace.

Hello, Objective-C

Now, here is the Objective-C version of "Hello World!" offered by Xcode:
//
// main.m
// Hello World Plus
//
// Created by Scott Wyatt on 2013-04-04.
// Copyright (c) 2013 Tameri Publications. All rights reserved.
//

#import

int main(int argc, const char * argv[])
{

@autoreleasepool {

// insert code here...
NSLog(@"Hello, World!");

}
return 0;
}
The Objective-C version of "Hello World!" is familiar to C programmers, but still different enough to reveal ways in which Objective-C is not C. All the following information is technical. It will be useful, later.

import vs. include

In Objective-C, it is a good idea to use the compiler directive import instead of include. You might say that include is rather "brain dead" — it can muck up the works if you accidentally include the same source code more than once. When you import code, the compiler verifies that you have the code only once in your application. For now, that's a little detail. When you are working on large projects, include mistakes are easier to make.

Also, look at what is imported by Xcode. The "Foundation.h" header actually imports several dozen smaller header files. This is the magic of importing: you can reuse code easily.

If you want to be overwhelmed:

http://stackoverflow.com/questions/959007/files-imported-when-importing-foundation-foundation-h-for-cocoa

@autoreleasepool

Don't worry about @autoreleasepool{} for now. It does some memory magic that's beyond what I'm going to address in any pending blog posts. Leave it, and its curly braces, alone.

NSLog() vs. printf()

Again, beginning Cocoa programmers don't need to worry about the details yet, but NSLog() is going to be your friend when you are working on big applications. Sure, there are other ways to debug code, but nothing beats getting some output along the way.

The NSLog() function sends output to the console window or the debug area in Xcode. If you are writing a true command line tool, I would suggest using printf(). If you are only using the output to debug an application, use NSLog().

Much of what you learn about printf() in my upcoming blog posts will apply to NSLog(). Plus, by learning about printf() you are learning generic C code that works with any standard C compiler.

Comments

Popular posts from this blog

Slowly Rebooting in 286 Mode

The lumbar radiculopathy, which sounds too much like "ridiculously" for me, hasn't faded completely. My left leg still cramps, tingles, and hurts with sharp pains. My mind remains cloudy, too, even as I stop taking painkillers for the back pain and a recent surgery.

Efforts to reboot and get back on track intellectually, physically, and emotionally are off to a slow, grinding start. It reminds me of an old 80286 PC, the infamously confused Intel CPU that wasn't sure what it was meant to be. And this was before the "SX" fiascos, which wedded 32-bit CPU cores with 16-bit connections. The 80286 was supposed to be able to multitask, but design flaws resulted in a first-generation that was useless to operating system vendors.

My back, my knees, my ankles are each making noises like those old computers.

If I haven't already lost you as a reader, the basic problem is that my mind cannot focus on one task for long without exhaustion and multitasking seems…

MarsEdit and Blogging

MarsEdit (Photo credit: Wikipedia) Mailing posts to blogs, a practice I adopted in 2005, allows a blogger like me to store copies of draft posts within email. If Blogger, WordPress, or the blogging platform of the moment crashes or for some other reason eats my posts, at least I have the original drafts of most entries. I find having such a nicely organized archive convenient — much easier than remembering to archive posts from Blogger or WordPress to my computer.

With this post, I am testing MarsEdit from Red Sweater Software based on recent reviews, including an overview on 9to5Mac.

Composing posts an email offers a fast way to prepare draft blogs, but the email does not always work well if you want to include basic formatting, images, and links to online resources. Submitting to Blogger via Apple Mail often produced complex HTML with unnecessary font and paragraph formatting styles. Problems with rich text led me to convert blog entries to plaintext in Apple Mail and then format th…

Screenwriting Applications

Screenplay sample, showing dialogue and action descriptions. "O.S."=off screen. Written in Final Draft. (Photo credit: Wikipedia) A lot of students and aspiring writers ask me if you "must" use Final Draft or Screenwriter to write a screenplay. No. Absolutely not, unless you are working on a production. In which case, they own or your earn enough for Final Draft or Screenwriter and whatever budget/scheduling apps the production team uses.

I have to say, after trying WriterDuet I would use it in a heartbeat for a small production company and definitely for any non-profit, educational projects. No question. The only reason not to use it is that you must have the exclusive rights to a script... and I don't have those in my work.

WriterDuet is probably best free or low-cost option I have tested. It is very interesting. Blows away Celtx. The Pro version with off-line editing is cheaper than Final Draft or Screenwriter.

The Pro edition is a standalone, offline versio…