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.
Here is the complete C version of "Hello World!" created by Xcode:
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.
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.
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:
What if you don't care about a return value? Many simple main() functions are written in the format:
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:
How does C know you might (or might not) include parameters and switches?
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.
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
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.
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:
- main() is a function that returns an integer value.
- If the user executing this program has included "command line arguments" after the application's name, please store those arguments for later processing.
- Execute the code within the curly-braces.
- Return the integer value "0" via main() when finished.
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 /wThe 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.
ls -l
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://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.
// 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;
}
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
Post a Comment