Learn C Programming

4.4 (5 reviews total)
By Jeff Szuhay
    What do you get with a Packt Subscription?

  • Instant access to this title and 7,500+ eBooks & Videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Free Chapter
    Running Hello, World!
About this book

C is a powerful general-purpose programming language that is excellent for beginners to learn. This book will introduce you to computer programming and software development using C. If you're an experienced developer, this book will help you to become familiar with the C programming language.

This C programming book takes you through basic programming concepts and shows you how to implement them in C. Throughout the book, you'll create and run programs that make use of one or more C concepts, such as program structure with functions, data types, and conditional statements. You'll also see how to use looping and iteration, arrays, pointers, and strings. As you make progress, you'll cover code documentation, testing and validation methods, basic input/output, and how to write complete programs in C.

By the end of the book, you'll have developed basic programming skills in C, that you can apply to other programming languages and will develop a solid foundation for you to advance as a programmer.

Publication date:
June 2020
Publisher
Packt
Pages
646
ISBN
9781789349917

 
Understanding Program Structure

A C program, as in most programming languages, consists of a sequence of small, individual pieces of computational work called statements, which are formed into larger building blocks called functions, which are then compiled into a single program. As we examine these programming elements, we will expand on the main() function, which we encountered in the previous chapter.

The following topics will be covered in this chapter:

  • Introducing the building blocks of programs – statements and blocks
  • Introducing the various kinds of C statements
  • Understanding delimiters
  • Using whitespace to make your program easier to read for humans
  • Introducing functions and their parts
  • Learning how a computer reads a C program as it runs
  • Creating various kinds of functions with parameters and return values
  • Learning...
 

Technical requirements

Throughout the rest of this book, unless otherwise mentioned, you will continue to use your computer with the following:

  • A plaintext editor of your choice
  • A console, terminal, or command-line window (depending on your OS)
  • A compiler—either the GNU Compiler Collection (GCC) or Clang (clang) for your particular OS

For consistency, it is best if you use the same computer and programming tools for all of the exercises. By doing so, you can focus more closely on the details of C on your computer.

The source code for this chapter can be found athttps://github.com/PacktPublishing/Learn-C-Programming. Continue to type in the source code completely yourself and get your version of the programs to run it correctly.

 

Introducing statements and blocks

Before we begin to explore the details of statements, let's return to the various uses of punctuation that we encountered in our Hello, world! program. Here is the program for reference; comments have been removed so that we can concentrate on the details of the code itself:

#include<stdio.h>
int main() {
printf( "Hello, world!\n" );
return 0;
}

At first, I'd like to draw your attention to the paired punctuation—the punctuation that occurs with a beginning mark and a very similar ending mark. Going through it line by line, we see the following pairs—< and >, ( and ) (which occur twice), { and }, and finally, " and ". We also see some other punctuation that may or not be familiar to you. These are #, ., ;, \, <space>, and <newline>. These are punctuation marks that are significant in the C language.

When we look closely at our "Hello, world!\n&quot...

 

Experimenting with statements and blocks

What happens on your system when you replace \n with \r? The most likely result is that it will appear as if no greeting was printed at all. If that is the case, what actually happened is the text printing focus went back to the beginning of the line but the line was not advanced; the console prompt wrote over it, wiping out our greeting. If you want to advance to the next line without returning to the beginning of the line, try the <linefeed> character, or \v.

Digraphs that appear in strings are also called escape sequencesbecause they escape from the normal meaning of each single character. They all begin with the backslash (\) character. The following table shows the legal C digraphs:

...
Symbol Meaning
\a Alert
 

Understanding delimiters

Delimiters are characters used to separate smaller parts of the program from one another. These smaller parts are called tokens. A token is the smallest complete C language element. A token is either a single character or a sequence of characters predefined by the C language, such as int or return, or a sequence of characters/words defined by us, which we will learn about later. When a token is predefined by C, it cannot be used except in a prescribed way. These tokens are called keywords. Four keywords we have already encountered are include, int, main, and return. We will encounter many others throughout the course of this chapter.

Again, here is the Hello, world! program for reference:

#include<stdio.h>
int main() {
printf( "Hello, world!\n" );
return 0;
}

There are three types of delimiters that we will explore here:

  • Single delimiters: ; and <space>
  • Paired, symmetric delimiters...
 

Understanding whitespace

When a <space> or <newline> character is not required to delimit a portion of C code, it is considered whitespace. Whitespace can also be <tab>, <carriage return>, and some other obscure characters. However, the use of tabs in C source files is discouraged since the program listing may look different on someone else's computer or when the source code is printed, thereby diminishing clarity and obfuscating your original intent.

Always use spaces instead of tabs in your source code files.

We write <newline> to mean the start of a new line, which has the same effect as hitting Enter on your keyboard. <space> similarly is the same as hitting the spacebar at the bottom of your keyboard.

There are many opinions by as many programmers on how to effectively use whitespace. Some programmers feel strongly about using two spaces to indent a line while others are vehement about using four spaces. Others...

 

Introducing statements

Statements in C are the basic building blocks of programs; each statement forms a complete unit of computational logic. There are many types of statements and they are made up of a wide variety of elements:

  • Simple statements: End with ;. return 0; is a simple statement.
  • Block statements: Begin with { and end with }. They contain and group other statements. Here, we represent them as { … }, where represents one or more statements of any type of valid statement.
  • Complex statements: On the other hand, these consist of a keyword and one or more block statements. main(){…} is a complex statement; it has the main keyword and other pre-defined elements, including a block statement. Complex statements include functions (which are covered in this chapter), control statements (covered in Chapter 6, Exploring Conditional Program Flow), and looping statements (covered in Chapter 7, Exploring Loops and Iteration...
 

Introducing functions

Functions are callable segments of program code that perform one or more statements of related computational work. Functions group statements into a cohesive set of instructions that perform a specific, complex task. This may comprise a single statement, only a few statements, or many statements. Functions can also call other functions. Functions, made up of one or more statements, are the next, higher-up, more-complex units of program composition. Statements make functions; functions make programs. Indeed, main() is a function made of statements and other functions.

The process of writing programs—or rather, solving a given problem—with a computer program is primarily the task of breaking the problem down into smaller pieces—into functions—and focusing on the work to be done in each smaller piece. When we break a problem down into smaller parts, we can more easily see the essence of the problem. We can focus our attention...

 

Understanding function definitions

Functions, therefore, are an essential part of any C program. Each function that you will create has the following parts:

  • Function identifier: This is the name of the function. The name of the function should match closely to what it actually does.
  • Function result type or return value type: Functions can return a value to the caller; the caller may ignore the result. If a return value type is specified, the function must return a value of that type to the caller.
  • Function block: A block directly associated with the function name and parameter list where additional statements are added to perform the work of the function.
  • Return statement:The primary mechanism to return a value of the specified type from the called function to its caller.
  • Function parameter list: This is an optional list of values that are passed into the function, which it may use as a part of its calculation.
  • ...
 

Exploring function identifiers

So, main() is a function just like any other function. However, it does have some significant differences—the mainfunction identifier is reserved. The signature for it is also pre-defined in two specific ways. You cannot name any other function in your programmain. Your program can never call main itself;maincan only be called by the system.

Function identifiers should be descriptive of their purpose. You would expect the function named printGreeting() to print a greeting, as its name implies. Likewise, you would expect a function named printWord() to print a single word. Naming functions to match their purpose is a good programming practice. Naming functions any other way, say Moe(), Larry(), and Curly(), gives no real indication of what they do, even if somehow in your conception these three functions are related; this would be considered very bad programming practice.

Function identifiers are case sensitive. This meansmain...

 

Exploring the function block

The function block is where the work of the function happens.

Within the function block are one or more statements. In our Hello, world! main function, there are only two statements. In the following program, main.c, there is only one—the return 0; statement:

int main()  {
return 0;
}

While there is no ideal size, large or small, for the number of statements in a function block, typically, functions that are no longer than either the number of lines in a terminal, 25 lines, or a printed page, say 60 lines, are preferable to much longer functions. TheGoldilocks targetgiven multiple options, the one Goldilocks in the fairy taleGoldilocks and the Three Bearswould have chosen—in this case, would be somewhere between 25 and 50 lines. Shorter functions are most often preferred over much longer ones.

In some cases, however, longer functions are warranted. Rarely, if ever, are they considered good programming...

 

Exploring function return values

A function statement can return a value to its caller. It does so from within its function block. The caller is not required to use the returned value and can ignore it. In Hello, world!, the printf() function call actually does return a value but we ignore it.

When a function statement is specified with a return type, then it must return a value of that type. Such a specification consists of two parts:

  • The return type of the function, given before the name of the function
  • The return value, which is of the same type as the return type

In main.c, int—short for integer or whole number—is the type specified that the main()function must return to its caller. Immediately before the closing brace, we find thereturn 0;statement, which returns the 0integer value. In most OS system calls (such as Unix, Linux, macOS, and Windows), a return value of 0 by convention typically means no error...

 

Passing in values with function parameters

A function can be values givenas input to the function. It can then use them within the function body. When the function is defined, the type and number of parameters that can bepassed in or received by the functions are specified. When the function is called, the values of the parameters are given. The function call parameters must match the type and number of parameters specified. In other words, the function signature must match both the caller of the function and the called function.

We have already encountered a function that takes a parameter—the printf( "Hello, world!\n" ); function call. Here, the parameter is a string with the "Hello, world!\n"value. It could be almost any string, as long it is delimited by"".

Function parameters are specified in the function definition between the ( … ) delimiters. The ellipsis indicates that there can be zero or more function parameters...

 

Order of execution

When a program executes, it first finds main() and begins executing statements in the main() function block. Whenever a function call statement is encountered, a number of actions occur:

  1. If there are function parameters, the actual values found in the function call statement are assigned to the function parameter names.
  2. Program execution jumps to that function and begins executing statements in that function block.
  1. Execution continues until either a return statement is encountered or the end of the block is encountered (the closing }).
  2. Execution jumps back, or returns, to the calling function and resumes from that point.

If, in step 2, execution encounters another function call statement, the steps are repeated.

The following diagram illustrates the call/return order of execution when function calls are encountered. This order of execution cannot be violated. Since...

 

Understanding function declarations

In order for the compiler to recognize a function call when it sees it, it must already know about the function. In other words, it must already have processed the function statement's definition before it can process the call to that function. We have seen this behavior in all of our programs up to this point. In each program, we have defined the function, and then later in our program, we called it.

This behavior is somewhat limiting since we may want to call a function from anywhere in our program. We don't want to get caught up in its relative position in the program and have to reshuffle the definitions of the functions just to make the compiler happy. The compiler is supposed to work for us, not the other way around.

C provides a way to declare a function so that the compiler knows just enough about the function to be able to process a call to the function before it actually processes the function definition....

 

Summary

In this chapter, we began with a very simple C program and explored C statements. We expanded and changed our program through the use of functions. We saw how to define functions, call them, and declare function prototypes. Lastly, we saw how we can structure our programs using a top-down or bottom-up approach when implementing our program.

Thinking about solving a problem in terms of breaking it down into smaller pieces and solving each of them via functions is an essential skill to be able to solve complex problems in any programming language.

As we explore the remainder of the C syntax, we will demonstrate each feature through functions and further explore how we can change functions to make our programs either more appropriate to our problem or to make it easier to understand how the problem is being solved.

In the next chapter, we will begin to develop an understanding of data types. The data type determines how to interpret a value and what...

About the Author
  • Jeff Szuhay

    Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.

    Browse publications by this author
Latest Reviews (5 reviews total)
It is very good. Quite complete...
Well written, up to date and helpful.
uma boa ajuda para iniciantes
Recommended For You
Learn C Programming
Unlock this book and the full library FREE for 7 days
Start now