C Articles
The original. The OG. So fundamental they just call it "C." These articles will walk you through the basics of one of the most foundational computer languages in the world.
Articles From C
Filter Results
Article / Updated 08-04-2022
The programming adventure has its pitfalls and most C programmers can’t claim to be free of some mistakes. Many of them are common; the same mistakes, over and over. Even after decades of coding, C programmers often still find themselves doing stupid, silly things. Most often they’re done in haste — usually, simple things. But isn’t that the way of everything? Conditional Foul-Ups When you employ an if statement or initiate a while or for loop, the code makes a comparison. Properly expressing this comparison is an art form, especially when you try to do multiple things at once. My advice is to first split up the code before you load everything into the parentheses. For example: while((c=fgetc(dumpme)) != EOF) The code on the preceding line works, but before you get there, try this: c = 1; /* initialize c */ while(c != EOF) c=fgetc(dumpme); This improvement is more readable and less error prone. The situation grows more hair when you use logical operators to combine conditions. It’s highly recommended that you limit the expression to two choices only: if( a==b || a==c) The statements belonging to if are executed when the value of variable a is equal to either the value of variable b or variable c. Simple. But what about this: if( a==b || a==c && a==d) Oops. Now the order of precedence takes over, and for the if statement to be true, a must be equal to b, or a must be equal to both c and d. The situation can also be improved by using parentheses: if( a==b || (a==c && a==d)) When you’re unsure about the order of precedence, use parentheses. == v. = A single equal sign is the assignment operator: a=65; A double equal sign is used for comparison: a==65 To get your brain to appreciate the difference, in your head you can say “is equal to” when you type two equal signs. Despite this reminder, it’s still easy to goof up, especially in a conditional statement. When you assign a value in a conditional statement, you generally create a TRUE condition unless the result of the assignment is zero: if(here=there) This if statement evaluates to the value of variable there. If it’s 0, the if condition evaluates as FALSE; otherwise, it’s true. Regardless, it’s most likely not what you intended. Most compilers, such as clang, catch this mistake. Dangerous loop semicolons in your C code You can get into a rut when you’re typing code, using the semicolon as a prefix before typing the Enter key to end a line. This practice has unintended consequences! It’s especially toxic when you code loops: for(x=0;x<10;x++); This loop works, but its statements aren’t repeated. When it’s done, the value of variable x is 10. That’s it. The same problem exists for a while loop: while(c<255); This loop may spin endlessly, depending on the value of variable c. If the value is greater than or equal to 255, the loop won’t execute. Otherwise, it executes forever. These semicolons are unintentional and unwanted. They’re also perfectly legitimate; the compiler doesn’t flag them as errors, though you may see a warning — which is quite helpful. For example, the suggested resolution is to place the semicolon on the next line: while(putchar(*(ps++))) ; This sole semicolon on a line by itself shouts to the compiler, as well as to any programmer reading the code, that the while loop is intentionally empty. Commas in a C for loop The three items in a for loop’s parentheses are separated by semicolons. Both those semicolons are required, and they are not commas. The compiler doesn’t like this statement: for(a=0,a<10,a++) Because commas are allowed in a for statement, the compiler merely thinks that you’ve omitted the last two required items. In fact, the following is a legitimate for statement: The preceding statement assigns the value 0 to variable a, generates a TRUE comparison (which is ignored), and increments the value of a to 1. Then, because the second and third items are empty, the loop repeats endlessly. (Well, unless a break statement belongs to the loop.) Missing break in a switch structure It’s perfectly legitimate to write a switch structure where the execution falls through from one case statement to the other: In this example, the first five case conditions capture the same set of statements. When you forget the break, however, execution falls through with more tests and, eventually, the default. Unless this control is what you want, remember to add break statements as necessary. Suppose that you have a switch structure that’s several dozen lines high. One case condition has multiple rows of statements, so many that it scrolls up and off the screen. In such a setup, it’s easy to forget the break as you concentrate instead on crafting the proper statements. I know — I’ve done it. Another situation happens when you code a loop inside a switch structure and you use break to get out of that loop. This inner break escapes from the for loop, only: A second break is required in order to get out of the switch structure. Many editors, such as the one used in Code::Blocks, let you collapse and expand parts of your code. To make this feature work in a switch structure, you must enclose the case statements in curly brackets. Missing parentheses and curly brackets in your C code Forgetting a parenthesis or two is one of the most common C coding mistakes. The compiler catches it, but usually the error isn’t flagged until the end of the function. For example, a missing parenthesis in the main() function causes the error to be flagged at the final line of the function. This warning is a good clue to a missing parenthesis or curly bracket, but it doesn’t help you locate it. Today’s editors are good at matching up parentheses and brackets. For example, the Code::Blocks editor inserts both characters when you type the first one. This feature helps keep things organized. Other editors, such as vim, highlight both sets of brackets when the cursor hovers over one. Use these hints as you type to ensure that things match up. Another editor clue is that the formatting, text coloring, and indents screw up when you forget a parenthesis or bracket. The problem with recognizing this reminder is that the human brain automatically assumes that the editor has screwed up. So you need to train yourself to recognize improper indentation by the editor as a sign of a missing parenthesis or curly bracket. Don’t ignore a warning from your C program When the compiler generates a warning, the program (or object code) is still created. This condition can be dangerous, especially when dealing with pointer errors. The problem is that warnings can be ignored; the code compiles anyway. For example, you may be using printf() to display a value that you know is an int, but somehow the compiler insists that it’s some other value. If so, you can typecast the variable as an int. For example: printf("%-14s %5ld %s", file->d_name, (long)filestat.st_size, ctime(&filestat.st_mtime)); In this example, the filestate.st_size variable is of the off_t data type. The printf() function lacks a conversion character for off_t, so it has typecast it to a long int. Similar typecasting can be done with other variable types for which printf() lacks a conversion character. But before you go nuts with this trick, check the man page for printf() to ensure that the specific data type lacks a conversion character. A common warning happens when you try to display a long int value by using the %d When that happens, just edit %d to %ld. An “lvalue required” warning indicates that you’ve written a malformed equation. The lvalue is the left value, or the item on the left side of the equation. It must be present and be of the proper type so that the equation is properly handled. The degree to which the compiler flags your code with warnings can be adjusted. Various flags are used to adjust the compiler’s warning level. These flags are set in the Code::Blocks IDE by choosing the Project→Build Options command. The Compiler Flags tab in the Project Build Options dialog box lets you set and reset the various warnings. The “turn on all warnings” option for a command-line C compiler is the -Wall It looks like this: clang -Wall source.c - Wall stands for “warnings, all.” Endless loops in C There’s got to be a way outta here, which is true for just about every loop. The exit condition must exist. In fact, it’s highly recommended that when you set out to code a loop, the first thing you code is the exit condition. As long as it works, you can move forward and write the rest of the joyous things that the loop does. Unintentional endless loops do happen. C programmers run code many times, only to watch a blank screen for a few moments. Oops. Console applications, such as the kind created throughout this book, are halted by pressing the Ctrl+C key combination in a terminal window. This trick may not always work, so you can try closing the window. You can also kill the task, which is a process that’s handled differently by every operating system. For example, in a Unix operating system, you can open another terminal window and use the kill command to rub out a program run amok in the first terminal window. scanf() blunders in C The scanf() function is a handy way to read specific information from standard input. It’s not, however, ideal for all forms of input. For example, scanf() doesn’t understand when a user types something other than the format that’s requested. Specifically, you cannot read in a full string of text. This issue is because scanf() discards any part of the string after the first white space character. Though the fgets() function is a great alternative for capturing text, keep in mind that it can capture the newline that ends a line of text. This character, \n, becomes part of the input string. The other thing to keep in mind when using scanf() is that its second argument is an address, a pointer. For standard variable types — such as int, float, and double — you must prefix the variable name with the &, the address operator: scanf("%d",&some_int); The & prefix isn’t necessary for reading in an array: scanf("%s",first_name); Individual array elements, however, aren’t memory locations, and they still require the & prefix: scanf("%c",&first_name[0]); Pointer variables do not require the & prefix, which could result in unintended consequences. Streaming input restrictions in C The basic input and output functions in the C language aren’t interactive. They work on streams, which are continuous flows of input or output, interrupted only by an end-of-file marker or, occasionally, the newline character. When you plan to read only one character from input, be aware that the Enter key, pressed to process input, is still waiting to be read from the stream. A second input function, such as another getchar(), immediately fetches the Enter key press (the \n character). It does not wait, as an interactive input function would. If you desire interactive programs, get a library with interactive functions, such as the NCurses library. The end-of-file marker is represented by the EOF constant, defined in the h header file. The newline character is represented by the \n escape sequence. The newline character’s ASCII value may differ from machine to machine, so always specify the escape sequence \n for the newline. Want to learn more? Check out our C Programming Cheat Sheet.
View ArticleArticle / Updated 08-04-2022
It’s difficult to narrow down the list of reminders and suggestions, especially for a topic as rich and diverse as programming. For example, an expert could suggest ways to fit in with other programmers, which movies to quote, which games to play, and even which foods to eat. A programming subculture exists — even today, though the emphasis on professional workplace attire has thankfully abated. Beyond social suggestions, there are a few things to remind you of — plus, some general-purpose C programming language recommendations. Believe it or not, every programmer has been through the same things you’ve experienced. It’s good to hear advice from a grizzled programming veteran. Maintain good posture when you’re programming Someone in your early life probably drilled into you the importance of having proper posture. Ignore them at your own peril, especially when you’re young and haven’t yet gotten out of bed to say, “Ouch.” For many programmers, coding becomes an obsession. For most C programmers, it’s quite easy to sit and write code for many hours straight. Such a stationary position is hard on the body. So, every few minutes, take a break. If you can’t manage that, schedule a break. Seriously: The next time you compile, stand up! Look outside! Walk around a bit! While you’re working, try as hard as you can to keep your shoulders back and your wrists elevated. Don’t crook your neck when you look at the monitor. Don’t hunch over the keyboard. Look out a window to change your focus. Remember that it’s pleasant to acknowledge others. True, it’s easy to grunt or snarl at someone when you’re in the midst of a project. Keep in mind that other humans may not appreciate the depth of thought and elation you feel when you code. If you can’t be pleasant now, apologize later. Use creative names in your C programs The best code reads like a human language. It’s tough to make the entire source code read that way, but for small snippets, having appropriate variable and function names is a boon to writing clear code. For example, the following expression is a favorite: while(!done) You can read this statement as “while not done.” It makes sense. Until the value of the donevariable is TRUE, the loop spins. But somewhere inside the loop, when the exit condition is met, the value of done is set equal to TRUE and the loop stops. It’s lucid. It also helps to offer descriptive names to your C functions. A name such as setringervolume() is great, but the name set_ringer_volume() is better. It also helps to consider the function in context. For example: ch=read_next_character(); In the preceding line, the function read_next_character() needs no explanation — unless it doesn’t actually return the next character. Write a function in C Anytime you use code more than once, consider throwing it off into a function, even if the code is only one line long or appears in several spots and doesn’t really seem function-worthy. Suppose that you use the fgets() function to read a string, but then you follow fgets() with another function that removes the final newline character from the input buffer. Why not make both items their own function, something like get_input()? Work on your C code a little bit at a time A majority of the time you spend coding is to fix problems, to correct flaws in logic, or to fine-tune. When making such adjustments, avoid the temptation to make three or four changes at one time. Address issues one at a time. The reason for the admonition is that it’s tempting to hop around your code and work on several things at a time. For example: You need to fix the spacing in a printf() statement’s output, adjust a loop, and set a new maximum value. Do those things one at a time! When you attempt to do several things at a time, you can screw up. But which thing did you goof up? You have to go back and check everything, including the related statements and functions, to ensure they work. During situations like these, you will seriously wish for a time machine. Instead, just work on your code a little bit at a time. Break apart larger C projects into several modules No one likes to scroll through 500 lines of code. Unless you’re totally immersed in your project and can keep everything stored in your noggin, break out functions into modules. Many C programmers prefer to group related functions into similar files. C programmers typically have an output file, an input file, an initialization file, and so on. Each file, or module, is compiled and linked separately to form the code. The benefits are that the files are smaller and if they compile and work, you no longer need to mess with them. Know what a pointer is in C A pointer is a variable that stores a memory location. It’s not magic, and it shouldn’t be confusing, as long as you keep the basic mantra in your head: A pointer is a variable that stores a memory location. A memory location stored in a pointer references another variable or a buffer (like an array). Therefore, the pointer must be initialized before it’s used: A pointer must be initialized before it’s used. When the pointer variable in C is prefixed by the *(asterisk) operator, it references the contents of the variable at the memory location. This duality is weird, of course, but it’s highly useful. Declare a pointer variable by using the * Use the & operator to grab the address of any variable in C. Arrays are automatically referenced by their memory locations, so you can use an array name without the & prefix to grab its address. “Address” and “memory location” are the same thing. A great way to explore pointers is to use the Code::Blocks debugger; specifically, the Watches window. Add white space before condensing your C code C programmers love to bunch up statements, cramming as many of them as they can into a single line, such as while(putchar(*(sample++))) Admit it: Such a construction looks cool. It makes it seem like you really know how to code C. But it can also be a source of woe. My advice: Split out the code before you condense it. Make liberal use of white space, especially when you first write the code. For example, the line if( c != '\0' ) is easier to read than the line if(c!='\0') After you write your code with white space — or use several statements to express something — you can condense, move out the spaces, or do whatever else you like. In C language source code, white space is for the benefit of human eyes. I admire programmers who prefer to use white space over cramming their code onto one line, despite how interesting it looks. Know when if-else becomes switch-case Many C programmers are big fans of the if-else decision tree, but they generally avoid stacking up multiple if statements. It usually means that the programming logic is flawed. For example: if(something) ; else if(something_else) ; else(finally) ; This structure is okay, and it’s often necessary to deal with a 3-part decision. But the following structure, which has been built by many budding C programmers, probably isn’t the best way to code a decision tree: if(something) ; else if(something_else_1) ; else if(something_else_2) ; else if(something_else_3) ; else if(something_else_4) ; else(finally) ; Generally speaking, anytime you have that many else-if statements, you probably need to employ the switch-case structure instead. In fact this example is probably what inspired the switch-case structure in the first place. Remember assignment operators in the C language Though it’s nice to write readable code, one handy tool in the C language is an assignment operator. Even if you don’t use one, you need to be able to recognize it. The following equation is quite common in programming: a = a + n; In C, you can abbreviate this statement by using an assignment operator: a += n; The operator goes before the equal sign. If it went afterward, it might change into a unary operator, which looks weird: a =+ n; So the value of variable a equals positive n? The compiler may buy that argument, but it’s not what you intended. Also, don’t forget the increment and decrement operators, ++ and --, which are quite popular in loops. When you get stuck, read your code out loud To help you track down that bug, start reading your code aloud. Pretend that a programmer friend is sitting right next to you. Explain what your code is doing and how it works. As you talk through your code, you’ll find the problem. If you don’t, have your imaginary friend ask you questions during your explanation. Don’t worry about going mental. You’re a C programmer. You’re already mental. As a bonus, talking through your code also helps you identify which portions need to have comments and what the comments should be. For example: a++; /* increment a */ In the preceding line, you see a terrible example of a comment. Duh. Of course, a is incremented. Here’s a better version of that comment: a++; /* skip the next item to align output */ Don’t just comment on what the code is doing — comment on why. Again, pretend that you’re explaining your code to another programmer — or to future-you. Future-you will thank present-you for the effort. Want to learn more? Check out our C Programming For Dummies Cheat Sheet.
View ArticleCheat Sheet / Updated 03-23-2022
When you write an Objective-C program for your iOS or Mac OS X apps, all you're doing is providing a set of instructions for the computer to follow. Fundamentally, programs manipulate numbers and text, and all things considered, a computer program has only two parts: variables (and other structures), which "hold" the data, and instructions, which perform operations on that data. This Cheat Sheet provides some of the main aspects of Objective-C programming, including making a statement, built-in and new data types, operators, and more.
View Cheat SheetArticle / Updated 04-06-2021
Another popular looping keyword in C programming is while. It has a companion, do, so programmers refer to this type of loop as either while or do-while. The C language is missing the do-whacka-do type of loop. How to structure a while loop in C programming The C language while loop is a lot easier to look at than a for loop, but it involves more careful setup and preparation. Basically, it goes like this: while(<i>condition</i>) { statement(s); } The condition is a true/false comparison, just like you’d find in an if statement. The condition is checked every time the loop repeats. As long as it’s true, the loop spins and the statement (or statements) between the curly brackets continues to execute. Because the evaluation (condition) happens at the start of the loop, the loop must be initialized before the while statement, as shown in Write That Down Ten Times! So how does a while loop end? The termination happens within the loop’s statements. Usually, one of the statements affects the evaluation, causing it to turn false. After the while loop is done, program execution continues with the next statement after the final curly bracket. A while loop can also forgo the curly brackets when it has only one statement: while(<i>condition</i>) statement; WRITE THAT DOWN TEN TIMES! #include <stdio.h> int main() { int x; x=0; while(x<10) { puts("Sore shoulder surgery"); x=x+1; } return(0); } The while loop demonstrated has three parts: The initialization takes place on Line 7, where variable x is set equal to 0. The loop’s exit condition is contained within the while statement’s parentheses, as shown in Line 8. The item that iterates the loop is found on Line 11, where variable x is increased in value. Or, as programmers would say, “Variable x is incremented.” Exercise 1: Create a new project, ex0913, using the source code from Write That Down Ten Times!. Build and run. Exercise 2: Change Line 7 in the source code so that variable x is assigned the value 13. Build and run. Can you explain the output? Exercise 3: Write a program that uses a while loop to display values from –5 through 5, using an increment of 0.5. How to use the do-while loop in C programming The do-while loop can be described as an upside-down while loop. That’s true, especially when you look at the thing’s structure: do { statement(s); } while (<i>condition</i>); As with a while loop, the initialization must take place before entering the loop, and one of the loop’s statements should affect the condition so that the loop exits. The while statement, however, appears after the last curly bracket. The do statement begins the structure. Because of its inverse structure, the major difference between a while loop and a do-while loop is that the do-while loop is always executed at least one time. So you can best employ this type of loop when you need to ensure that the statements spin once. Likewise, avoid do-while when you don’t want the statements to iterate unless the condition is true. A FIBONACCI SEQUENCE #include <stdio.h> int main() { int fibo,nacci; fibo=0; nacci=1; do { printf("%d ",fibo); fibo=fibo+nacci; printf("%d ",nacci); nacci=nacci+fibo; } while( nacci < 300 ); putchar('n'); return(0); } Exercise 4: Type the source code from A Fibonacci Sequence into a new project, ex0916. Mind your typing! The final while statement (refer to Line 16) must end with a semicolon, or else the compiler gets all huffy on you. Here’s the output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 The loop begins at Lines 7 and 8, where the variables are initialized. Lines 12 through 15 calculate the Fibonacci values. Two printf() functions display the values. The loop ends on Line 16, where the while statement makes its evaluation. As long as variable nacci is less than 300, the loop repeats. You can adjust this value higher to direct the program to output more Fibonacci numbers. On Line 18, the putchar() statement cleans up the output by adding a newline character. Exercise 5: Repeat Exercise 2 as a do-while loop.
View ArticleCheat Sheet / Updated 03-09-2021
The best way to learn programming is to start with a fundamental language like C. Nearly every other popular language today borrows from C. Whether you’re curious about programming, need to pass a college course, or want to start your own app business, learning C is the right place to begin.
View Cheat SheetArticle / Updated 03-26-2016
Each program must have a starting point. When you run a program, DOS sends it off on its way — like launching a ship. As its last dock-master duty, DOS hurls the microprocessor headlong into the program. The microprocessor then takes the program's helm at that specific starting point. In all C programs, the starting point is the main() function. Every C program has one, even GOODBYE.C (shown in Figure 1). The main() function is the engine that makes the program work, which displays the message on the screen. Figure 1: GOODBYE.C and its pieces and parts. Other C programs may carry out other tasks in their main() function. But whatever's there, it's the first instruction given to the computer when the program runs. main() is the name given to the first (or primary) function in every C program. C programs can have other functions, but main() is the first one. It's a common convention to follow a C language function name with parentheses, as in main(). It doesn't mean anything. Everyone does it, and it's included here so that you don't freak when you see it elsewhere. In Borland C++, you may have seen the error message say "in function main." This message refers to the main function — the void main() thing that contains the C language instructions you've been writing. A function is a machine — it's a set of instructions that does something. C programs can have many functions in them, though the main function is the first function in a C program. It's required. Function. Get used to that word. Pieces' parts Here are some interesting pieces of the C program shown in Figure 1: 1. #include is known as a preprocessor directive, which sounds impressive, and it may not be the correct term, but you're not required to memorize it anyhow. What it does is tell the compiler to "include" another program or file along with your source code, which generally avoids a lot of little, annoying errors that would otherwise occur. 2. is a filename hugged by angle brackets (which is the C language's attempt to force you to use all sorts of brackets and whatnot). The whole statement #include tells the compiler to use the file STDIO.H, which contains standard I/O, or input/output, commands required by most C programs. 3. void main identifies the name of the function main. The void identifies the type of function or what the function produces. In the case of main, it doesn't produce anything, and the C term for that is "void." 4. Two empty parentheses follow the function name. Sometimes, there may be items in these parentheses. 5. The curly brackets or braces enclose the function, hugging in tight all its parts. Everything between { and } is part of the function main() in Figure 1. 6. printf is a C language instruction, part of the programming language that eventually tells the computer what to do. 7. Belonging to printf are more parentheses. In this case, the parentheses enclose text, or a "string" of text. Everything between the double quotes (") is part of printf's text string. 8. An interesting part of the text string is n. That's the backslash character and a little n. What it represents is the character produced by pressing the Enter key. What it does is to end the text string with a "new line." 9. Finally, the printf line, or statement, ends with a semicolon. The semicolon is how the C compiler knows when one statement ends and another begins — like a period at the end of a sentence. Even though printf is the only instruction in this program, the semicolon is still required. • Text in a program is referred to as a string. For example, "la-de-da" is a string of text. The string is enclosed by double quotes. • The C language is composed of keywords that appear in statements. The statements end in semicolons, just as sentences in English end in periods.) The C language itself — the keywords The C language is really rather brief. There are only 33 keywords in C. If only French were that easy! Table 1 shows the keywords that make up the C language. Table 1: C Language Keywords asm enum signed auto extern sizeof break float static case for struct char goto switch const if typedef continue int union default long unsigned do register void double return volatile else short while Not bad, eh? But these aren't all the words you find in the C language. Other words or instructions are called functions. These include jewels like printf and several dozen other common functions that assist the basic C language keywords in creating programs. If you're using DOS, additional functions specific to DOS are piled on top of the standard C armada of functions. And if you get into Windows, you find hoards of Windows-specific functions that bring C's full vocabulary into the hundreds. And no, you don't really have to memorize any of them. This is why all C compilers come with a language reference, which you'll undoubtedly keep close to your PC's glowing bosom. Languages are more than a collection of words. They also involve grammar, or properly sticking together the words so that understandable ideas are conveyed. This concept is completely beyond the grasp of the modern legal community. In addition to grammar, languages require rules, exceptions, jots and tittles, and all sorts of fun and havoc. Programming languages are similar to spoken language in that they have various parts and lots of rules. You will never be required to memorize the 33 keywords. In fact, of the 33 keywords, you may end up using only half on a regular basis. Some of the keywords are real words! Others are abbreviations or combinations of two or more words. Still others are cryptograms of the programmer's girlfriends' names. Each of the keywords has its own set of problems. You don't just use the keyword else, for example; you must use it in context. Functions like printf require a set of parentheses and lots of stuff inside the parentheses. (Don't fret over this right now; just nod your head and smile in agreement, "Yes, printf does require lots of stuff.") By the way, the fact that printf is a C function and not a keyword is why the #include thing is required at the beginning of a program. The STDIO.H file contains the instructions telling the compiler what exactly printf is and does. If you edit out the #include line, the compiler produces a funky "I don't know that printf thing" type of error.
View ArticleArticle / Updated 03-26-2016
Variables are what make your programs zoom. Programming just can't get done without them. So if you haven't been introduced to variables yet, here you go. Valerie Variable is a numeric variable. She loves to hold numbers — any number; it doesn't matter. Whenever she sees an equal sign, she takes to a value and holds it tight. But see another equal sign, and she takes on a new value. In that way, Valerie is a little flaky. You could say that Valerie's values vary, which is why she's a variable. Victor Variable is a string variable. He contains bits of text — everything from one character to several of them in a row. As long as it's a character, Victor doesn't mind. But which character? Victor doesn't care — because he's a variable, he can hold anything. Yes, there is a point here. There are two main types of variables in C: numeric variables that hold only numbers or values, and string variables that hold text, from one to several characters long. There are several different types of numeric variables, depending on the size and precision of the number. Before you use a variable, it must be declared. This is — oh, just read the next section. "Why must I declare a variable?" You are required to announce your variables to the C compiler before you use them. You do this by providing a list of variables near the beginning of the program. That way, the compiler knows what the variables are called and what type of variables they are (what values they can contain). Officially, this process is known as declaring your variables. For example: int count;char key;char lastname[30]; Three variables are declared here: an integer variable, count; a character variable, key; and a character variable, lastname, which is a string that can be as many as 30 characters long. Doing this at the beginning of the program tells the compiler several things. First, it says, "These things are variables!" That way, when the compiler sees lastname in a program, it knows that it's a string variable. Second, the declarations tell the compiler which type of variable is being used. The compiler knows that integer values fit into the count variable, for example. Third, the compiler knows how much storage space to set aside for the variables. This can't be done "on the fly" as the program runs. The space must be set aside as the compiler creates the program. Declare your variables near the beginning of your program, just after the line with the initial curly bracket. Cluster them all up right there. Obviously, you won't know all the variables a program requires before you write it. (Although they teach otherwise at the universities, such mental overhead isn't required from you.) So, if you need a new variable, use your editor to declare it in the program. Rogue variables generate syntax or linker errors (depending on how they're used). If you don't declare a variable, your program does not compile. The proper authorities issue a suitable complaint message. Most C programmers put a blank line between the variable declarations and the rest of the program. There's nothing wrong with commenting a variable to describe what it contains. For example: int count; /* busy signals from tech support. */ However, cleverly named variables may avoid this situation: int busysignals; Variable names verboten and not What you can name your variables depends on your compiler. There are a few rules, plus some names you cannot use for variables. When you break the rules, the compiler lets you know by flinging an error at you. To avoid that, try to keep the following guidelines in the back of your head when you create new variables: The shortest variable name is a letter of the alphabet. Use variable names that mean something. Single-letter variables are just hunky-dory. But index is better than i, count is better than c, and name is better than n. Short, descriptive variable names are best. Variables are typically in lowercase. (All of C is lowercase for the most part.) They can contain letters and numbers. Uppercase letters can be used in your variables, but most compilers tend to ignore the differences between upper- and lowercase letters. (You can tell the compiler to be case-sensitive by setting one of its options; refer to your programmer's manual.) You should not begin a variable name with a number. They can contain numbers, but you begin it with a letter. C lords use the underline, or "underscore," character in their variable names: first_name, zip_code, and so on. This technique is fine, though it's not recommended to begin a variable name with an underline. Avoid naming your variables the same as C language keywords or functions. Don't name your integer variable int, for example, or your string variable char. This may not generate an error with your compiler, but it makes your source code confusing. Also avoid using the single letters l (lowercase L) and o (lowercase O) to name variables. Little L looks too much like a 1 (one), and O looks too much like a 0 (zero). Don't give similar names to your variables. For example, the compiler may assume that forgiveme and forgivemenot are the same variable. If so, an ugly situation can occur. Buried somewhere in one of the massive tomes that came with your compiler are the official rules for naming variables. These rules are unique to each compiler.
View ArticleArticle / Updated 03-26-2016
When you create a program, you tell the computer what to do. Because the computer can't understand speech and because hitting it — no matter what emotional value that has for you — does little to the PC, your final line of communications is to write the computer a note — a file on disk. To create the note, you use a program called a text editor. This is a primitive version of a word processor, minus all the fancy formatting and printing controls. The text editor enables you type text — that's about all. Using your text editor, you create what's called a source code file. The only special thing about this file is that it contains instructions that tell the computer what to do. And although it would be nice to write instructions like "Make a funny noise," the truth is that you must write instructions in a tongue the computer understands. In this case, the instructions are written in the C language. After you finish writing the instructions, you save them in a file on disk. Have the first part of the filename be the name you want to give the final program. For example, if you were creating a game called UFO Kill, the source code file should have a first name of UFOKILL. The second part of the filename, the extension, must be C, for the C language. This is important! Most text files end in TXT or sometimes DOC. For the C language, your files must end in .C (dot-C), such as UFOKILL.C. The source code file is a text file on disk. It contains instructions for the computer that are written in the C programming language. You use a text editor to create the source code file. Most C compilers come with their own text editors. If yours did not, you can use a third-party text editor to do the job. (Some programmers prefer third-party text editors.) You can use a word processor to create your source code files. However, save the file as a "plain text" or "DOS text" or "ASCII" or "unformatted" file. (Using a word processor to create a source code file is a lot like using a 747 to drive to work; it's a little too much power for the job at hand.) The source code file ends with a C as its filename extension. The first part of the source code filename should be the name of the program you want to create. Be clever when you name your source code. The compiler After the source code is created and saved to disk, it must be translated into a language the computer can understand. This is a job for the compiler to do. The compiler is a special program that reads the instructions stored in the source code file. The compiler runs through each instruction and translates it into the secret code understood only by the computer's microprocessor. If all goes well and the compiler is duly pleased with your source code, it produces an object code file, a second file that's saved on disk. The object code file has the same first name as the source code file, but it ends in .OBJ (dot-OBJ). So for that UFO game, it would be UFOKILL.OBJ. If the compiler doesn't understand something, it displays an error message on the screen. At that point, you can gnash your teeth and sit and stew. Then go back and edit the source code file again, fixing whatever error the compiler found. (This isn't as tough as it sounds.) Then you attempt to compile the program again — you recompile. After the compiler does its job, the program isn't finished. A third step is required: linking. The linker The linker is a program, like the compiler. Its job is to create the final program file. What the linker does is to take the OBJ file created by the compiler and spruce it up, producing the final program file. That file ends with either a COM or EXE extension — which is how program files are identified under DOS. The first part of the program filename is the same as the first part of the source code filename. So if you start with UFOKILL.C, the compiler creates an object file, UFOKILL.OBJ, and then the linker creates the final program file, UFOKILL.EXE. In most DOS C compilers, both the compiler's and linker's jobs are done together, one after the other. You may occasionally see "compile" and "link" listed as two steps (which they are), but with your C compiler they may be combined into one. Like the compiler, when the linker sees something it can't figure out, it produces an error message. In that case, you have to decipher the error message and compile the program again (recompile). The program file ends in EXE, though it's possible to tell the linker to create COM files. You can refer to your linker's documentation for pulling off that trick. Yup, that's right: From starting with a single source code file, you end up with three files on disk: UFOKILL.C, UFOKILL.OBJ, and UFOKILL.EXE. Some compilers may anoint your hard drive with even more files.
View ArticleArticle / Updated 03-26-2016
One of the frustrating aspects of the C programming language is the C Numeric Data Type Puzzle. Unlike in real life, where you can just pull any number out of the ethers and be joyously happy with it, in C you must pull numbers from specific parts of the ethers based on which type of number it is. This makes the frustration factor begin rising, with the logical question, "What's a number type?" Okay. It isn't a "number type." It's a numeric data type, which is how you say, "number type" if you work at the Pentagon. You have to tell the C compiler which type of number you're using, because it thinks about numbers differently from the way humans do. For example, you have to know the following things about the number: Will it be a whole number — without a fraction or decimal part? How big will the number be (as in value-large, not big-on-the-page-large)? If the number does have a fractional part, how precise must the number be? (Like to the thousandths, millionths, or gazillionths decimal place. Scientists have to know such precision when they send rockets to outer space to go where no one has gone before.) Yes, this is all alien to you. What most programmers want to do is say, "I need a number variable — just give me one, quick — before this value slips out the back of the computer and becomes a government statistic!" But you have to think a little more before you do that. C uses a variety of number types — different numeric data types, so to speak. Table 1 lists them all, along with other statistical information. This table is something you'll refer to now and again because only the truly insane would memorize it all. Table 1: C Numeric Data Types Keyword Variable Type Range Storage Required char character (or string) –128 to 127 1 byte int integer –32768 to 32,767 2 bytes short (or short int) short integer –32768 to 32,767 2 bytes long long integer –2,147,483,648 to 2,147,483,647 4 bytes unsigned char unsigned character 0 to 255 1 byte unsigned int unsigned integer 0 to 65,535 2 bytes unsigned short unsigned short integer 0 to 65,535 2 bytes unsigned long unsigned long integer 0 to 4,294,967,295 4 bytes float single-precision floating point (accurate to 7 digits) + or -3.4 x 1038 to + or -3.4 x10-38 4 bytes double double-precision floating point (accurate to 15 digits) + or -1.7 x 10-308 to + or -1.7 x10308 8 bytes The keyword is the C language keyword used to declare the variable type. The variable type tells you which type of variable the keyword defines. For example, char defines a character (or string) variable; int does integers; and so on. There are many variable types, each of which depends on the type of number or value being described. The range tells you how big of a number will fit into the variable type. For example, integers range from –32,768 up to 0 and up again to 32,767. Other types of variables handle larger values. The Storage Required column tells you how many bytes of storage each variable type requires. This is advanced stuff, not really necessary to know. Some computer scientists can look at the bytes required and proclaim, "Goodness! An integer on a PC occupies 16 bits of storage. That must explain the 32K range. Indeed. Hmmm. Pass the nachos." Why use integers? Obviously, if you have a double-precision floating-point number that can handle, essentially, numbers up to 1 gazillion, why bother with the puny little integer? Heck, make everything a double-whammy floating point and be done with it! Sounds good. Is bad. Integers are truly the most common and handy types of numeric variables. Often, you need only small, whole-number values when you're programming. Floating-point numbers are okay, but they require more overhead from the computer and take longer to work with. By comparison, integers are far quicker. You have to concern yourself with only two types of integers: the normal integer — the int — and the long integer — the long. The int is a whole-number value, ranging from –32,768 to 32,767. It's ideally put to use for small numbers without a fractional part. In some versions of C, you may see this value referred to as a short or short int. In all DOS C compilers, it's just called int. (It rhymes with bent, not pint.) The long is a whole-number value, ranging from –2,147,483,648 to 2,147,483,647 — a big range, but not big enough to encompass the national debt or Madonna's ego. This type of numeric variable is referred to as a long, or long int in some versions of C. With DOS C compilers, you can freely mince about, calling it just long. In continuance with humankind's obsession with size, it would seem obvious — nay, greedy — to always want to use the long over the int. After all, bigger is better. Although that may be true, and psychologists can debate why most people feel that way, the truth is that the smaller the variable type you can get away with, the quicker your program runs. The int variables are tiny and tidy, easy for the computer to figure on its two thumbs. long variables require a little more time to compute, and it wastes the computer's memory and processing power to use them when you're better off with ints. (You'll see why this is so as you continue to program in C.) You use the int and long keywords to declare integer variables. int is for smaller values; long is for larger values. The %i placeholder is used in the printf function to display int variables. (You can also use the %d placeholder.) int = short = short int Integer variables (int) are shorter, faster, and easier for the computer to deal with. If Soup for One were a variable, it would be an int. Use int s whenever you need a small, whole numeric value. Negative numbers — why bother? Sometimes you need them, but most of the time you don't. The char variable type can also be used as a type of integer, though it has an extremely small range. These variables are used mostly to store single characters (or strings).
View ArticleArticle / Updated 03-26-2016
If you’re writing programs in C, you need to use comparison symbols. The symbols C uses, their meanings, and examples are shown in the following table: Symbol Meaning or Pronunciation “True” Comparison Examples < Less than 1 < 5 8 < 9 == Equal to 5 == 5 0 == 0 > Greater than 8 > 5 10 > 0 <= Less than or equal to 4 <= 5 8 <= 8 >= Greater than or equal to 9 >= 5 2 >= 2 != Not equal to 1 != 0 4 != 3.99
View Article