introduce you to C.
/*1*/ #include <stdio.h>
/*2*/
/*3*/ int main(void)
/*4*/ {
/*5*/ printf("Hello, world!\n");
/*6*/ return 0;
/*7*/ }
/*8*/
This program prints "Hello, world!" and then exits. The numbers are added for our benefit to refer to certain lines and would not be part of the real program.
Line 1 tells the C compiler to find a file called stdio.h and add the contents of that file to this
program. In C, you often have to pull in extra optional components when you need them. stdio.h
contains descriptions of standard input/output functions; in other words, stuff you can use to send messages to a user, or to read input from a user.
Line 3 is something you'll find in every C program. Every program has a main function. Generally,
the main function is where a program begins. However, one C program can be scattered across
multiple files, so you won't always find a main function in every file. The int at the beginning means that main will return an integer to whatever made it run when it is finished and void in the
parenthesis means that main takes no parameters (parameters to main typically come from a shell
when the program is invoked).
the main function is where a program begins. However, one C program can be scattered across
multiple files, so you won't always find a main function in every file. The int at the beginning means that main will return an integer to whatever made it run when it is finished and void in the
parenthesis means that main takes no parameters (parameters to main typically come from a shell
when the program is invoked).
Line 5 is the statement that actually sends the message to the screen. printf is a function that is
declared in the file stdio.h which is why you had to #include that at the start of the program. \n is a socalled escape code which adds a new line at the end of the printed text.
Line 6 will return zero (which is the integer referred to on line 3) to the operating system. When a
program runs successfully its return value is zero (GCC4 complains if it doesn't when compiling). A nonzero value is returned to indicate a warning or error.
Line 8 is there because it is (at least on UNIX) considered good practice to end a file with a new
line. ← A taste of C| Preliminaries →
line. ← A taste of C| Preliminaries →
Introductory Exercises
have GCC installed. Type the hello world program into a file called first.c and then compile it with gcc. Just type:
gcc first.c
Then run the program by typing:
./a.out
or
a.exe
if you are using cygwin.
There are a lot of options you can use with the gcc compiler. For example, if you want the output to have a name other than a.out, you can use the o option. Also, you can ask the compiler to print warnings while it handles your code. The following shows a few examples:
gcc Wall ansi pedantic o first first.c
All the options are well documented in the manual page for gcc and at even more length in the info material for gcc.
If you are using a commercial IDE you may have to select console project, and to compile you just select build from the menu or the toolbar. The executable will appear inside the project folder, but you should have a menu button so you can just run the executable from the IDE.
Beginning C
Basic Concepts
Before one jumps headlong into learning C syntax and programming constructs, it is beneficial to learn the meaning of a few key terms that are central to a thorough understanding of C. Good luck using this guide for your studies!
Compilation: How Does C Work?
Like any programming language, C by itself is completely incomprehensible to a microprocessor. Its
purpose is to provide an intuitive way for humans to provide instructions that can be easily
converted into machine code. The program you use to convert C code into executable machine code
is called a compiler [10]. If you are working on a project in which several source code files are
involved, a second program called the linker is invoked. The purpose of the linker is to "connect"
the files and produce either an executable program or a library. A library is a set of routines, not a
standalone program, but can be used by other programs or programmers. Compilation and linking
are so closely related that programmers usually treat them as one step. One thing to keep in mind is
that compilation is a "one way street"; compiling a C source file into machine code is easy, but
"decompiling" (turning machine code into the C source that creates it) is not. Decompilers for C do
exist, but they rarely create useful code. Probably the most popular compiler available is the GNU C
Compiler, which comes with most UNIX and UNIXlike systems.
purpose is to provide an intuitive way for humans to provide instructions that can be easily
converted into machine code. The program you use to convert C code into executable machine code
is called a compiler [10]. If you are working on a project in which several source code files are
involved, a second program called the linker is invoked. The purpose of the linker is to "connect"
the files and produce either an executable program or a library. A library is a set of routines, not a
standalone program, but can be used by other programs or programmers. Compilation and linking
are so closely related that programmers usually treat them as one step. One thing to keep in mind is
that compilation is a "one way street"; compiling a C source file into machine code is easy, but
"decompiling" (turning machine code into the C source that creates it) is not. Decompilers for C do
exist, but they rarely create useful code. Probably the most popular compiler available is the GNU C
Compiler, which comes with most UNIX and UNIXlike systems.
Integrated Development Environments (IDEs)
An IDE is a program that combines a set of programs that developers need into one convenient
package, usually with a graphical user interface. These programs include a compiler, linker, and text
editor. They also typically include a debugger, a tool that will preserve your C source code after
compilation and enable you to do such things as step manually through it or alter data in an attempt
to uncover errors. A very popular IDE is Microsoft Visual C++ (MS VC++); a popular free IDE is
DevC++, available at http://www.bloodshed.net. Also Pelles C at
editor. They also typically include a debugger, a tool that will preserve your C source code after
compilation and enable you to do such things as step manually through it or alter data in an attempt
to uncover errors. A very popular IDE is Microsoft Visual C++ (MS VC++); a popular free IDE is
DevC++, available at http://www.bloodshed.net. Also Pelles C at
http://www.smorgasbordet.com/pellesc/ (Don't be put off by the 'C++'; C++ is almost a superset of
C, so almost all C++ compilers also come with a C compiler, e.g. MS VC++ or GCC, the GNU
Compiler Collection.) If you are running Mac OS X the Xcode IDE is included on the Developer
Tools CD that came with your computer, you can also download it free at the Apple Developer
Connection. It is recommended you find a good IDE before you begin learning C (or any other
language), but you do not need one. If you have a decent text editor (Microsoft Word and
WordPerfect are not text editors, they are word processors. Notepad is a text editor though.) and a
compiler, they will do as well. There are many text editors (see List of Text Editors on Wikipedia),
the most popular being vi and its clones (such as vim) and Emacs.
C, so almost all C++ compilers also come with a C compiler, e.g. MS VC++ or GCC, the GNU
Compiler Collection.) If you are running Mac OS X the Xcode IDE is included on the Developer
Tools CD that came with your computer, you can also download it free at the Apple Developer
Connection. It is recommended you find a good IDE before you begin learning C (or any other
language), but you do not need one. If you have a decent text editor (Microsoft Word and
WordPerfect are not text editors, they are word processors. Notepad is a text editor though.) and a
compiler, they will do as well. There are many text editors (see List of Text Editors on Wikipedia),
the most popular being vi and its clones (such as vim) and Emacs.
Block Structure, Statements, Scope, and Whitespace
Now we discuss the basic structure of a C program. If you're familiar with PASCAL, you may
have heard it referred to as a block structured language. C does not have complete block structure
(and you'll find out why when you go over functions in detail) but it is still very important to
understand what blocks are and how to use them. A block is a group of source code statements
intended to control scope. In C, blocks begin with a "left curly" ("{") and end with a "right curly"
("}"). Blocks can contain subblocks, which can contain their own subblocks, and so on.
have heard it referred to as a block structured language. C does not have complete block structure
(and you'll find out why when you go over functions in detail) but it is still very important to
understand what blocks are and how to use them. A block is a group of source code statements
intended to control scope. In C, blocks begin with a "left curly" ("{") and end with a "right curly"
("}"). Blocks can contain subblocks, which can contain their own subblocks, and so on.
So what's in a block? Generally, a block consists of executable statements and the whitespace that surrounds them. A statement is text the compiler will attempt to turn into executable instructions. Statements always end with a semicolon (;) character. Multiple statements can share a single line in the source file. There are several kinds of statements, including assignment, conditional and flow control. A good portion of this book deals with statement construction.
Whitespace refers to the tab, space and newline/EOL (End Of Line) characters that separate the text characters that make up source code lines. Like many things in life, it's hard to appreciate
whitespace until it's gone. To a C compiler, the source code
whitespace until it's gone. To a C compiler, the source code
puts("Hello world"); return 0;
is the same as
puts("Hello world"); return 0;
is the same as
puts (
"Hello world") ;
return 0;
The compiler simply skips over whitespace. However, it is common practice to use spaces (and tabs)
to organize source code for human readability.
In C, most of the time we do not want other functions or other programmer's routines accessing data that we are currently manipulating. This is why it is important to understand the concept of scope. Scope describes the level at which a piece of data or a function can be seen or manipulated. There are two kinds of scope in C, local and global. When we speak of something being global, we speak of something that can be seen or manipulated from anywhere in the program. When we speak of
something being local, we speak of something that can be seen or manipulated only within the
block it was declared, or its subblocks. (Subblocks can access data local to their encompassing
block, but a block cannot access local data local to a subblock.)
something being local, we speak of something that can be seen or manipulated only within the
block it was declared, or its subblocks. (Subblocks can access data local to their encompassing
block, but a block cannot access local data local to a subblock.)
TIP: You can use blocks without an if, loop, et al statement to organize your code.
Basics of Using Functions
Functions are a big part of programming. A function is a special kind of block that performs a well defined task. If a function is welldesigned, it can enable a programmer to perform a task without
knowing anything about how the function works. The act of requesting a function to perform its task is called a function call. Many functions require a caller to hand it certain pieces of data needed to perform its task; these are called arguments. Many functions also return a value to the caller when they're finished; this is called a return value.
knowing anything about how the function works. The act of requesting a function to perform its task is called a function call. Many functions require a caller to hand it certain pieces of data needed to perform its task; these are called arguments. Many functions also return a value to the caller when they're finished; this is called a return value.
•
The things you need to know before calling a function are:
•
What the function does
• The data type (discussed later) of the arguments and what they mean
• The data type of the return value, and what it means
All code other than global data definitions and declarations needs to be a part of a function. Every executable program needs to have one and only one main function, which is where the program begins executing.
The Standard Library
In 1983, when C was in the process of becoming standardized, the standardization committee
decided that there needed to be a basic set of functions common to each implementation of C. This
is called the Standard Library. The Standard Library provides functions for tasks such as
input/output, string manipulation, mathematics, files, memory allocation, and more. The Standard
Library does NOT provide functions for anything that might be dependent on hardware or operating
system, like graphics, sound, or networking. In the "Hello, World", program, a Standard Library
function is used puts which outputs lines of text to the standard output stream.
is called the Standard Library. The Standard Library provides functions for tasks such as
input/output, string manipulation, mathematics, files, memory allocation, and more. The Standard
Library does NOT provide functions for anything that might be dependent on hardware or operating
system, like graphics, sound, or networking. In the "Hello, World", program, a Standard Library
function is used puts which outputs lines of text to the standard output stream.
Comments and Coding Style
Comments are text inserted into the source code of a program that serve no purpose other than documenting the code. In C, they begin with /* and end with */. Good commenting is considered essential to software development, not just because others may need to read your code, but you may need to come back to your code a long time after writing it and immediately understand how it
works. In general, it is a good idea to comment anything that is not immediately obvious to a
competent programmer. However, it is not a good idea to comment every line. This may actually make your code more difficult to read and it will waste space.
works. In general, it is a good idea to comment anything that is not immediately obvious to a
competent programmer. However, it is not a good idea to comment every line. This may actually make your code more difficult to read and it will waste space.
Good coding style habits are important to adopt for the simple reason that code should be intuitive and readable, which is, after all, the purpose of a highlevel programming language like C. In
general, provide ample white space, indent so that the opening brace of a block and the closing
brace of a block are vertically aligned, and provide intuitive names for your functions and variables. Throughout this text we will be providing more style and coding style tips for you. Do try and follow these tips: they will make your code easier for you and others to read and understand.
general, provide ample white space, indent so that the opening brace of a block and the closing
brace of a block are vertically aligned, and provide intuitive names for your functions and variables. Throughout this text we will be providing more style and coding style tips for you. Do try and follow these tips: they will make your code easier for you and others to read and understand.
The Preprocessor
Many times you will need to give special instructions to your compiler. This is done through
inserting preprocessor directives into your code. When you begin compiling your code, a
subprogram called the preprocessor first finds these directives and interprets them before the
compilation process begins. One thing to remember is that these directives are NOT compiled as
part of your source code. In C language, all preprocessor directives begin with the hash character
part of your source code. In C language, all preprocessor directives begin with the hash character
(#). You can see one preprocessor directive in "Hello, World!", #include. #include opens a file and conceptually replaces the #include directive with the file's contents. There is another common preprocessor directive, #define, that will be discussed later.
0 comments:
Post a Comment