 |
Cheat Engine The Official Site of Cheat Engine
|
| View previous topic :: View next topic |
| Author |
Message |
Nigtronix Cheater
Reputation: 0
Joined: 18 May 2007 Posts: 45
|
Posted: Fri Jun 01, 2007 7:59 pm Post subject: [Tutorial] Coding with C part 1 |
|
|
Coding With C : By silenthacker aka nigtronix on CE forums
Part #: 1
Originally published copyright 2004
Email: [email protected]
---------------------------------------------
You can use this tutorial freely, As long as you keep the above header unchanged. This article was originally published for another site by me, I revised some of it, and added some extra information.
.:An Introduction to the C programming Language Part1:.
Hello there fellow programmer, If you’re reading this tutorial I assume that you are a beginner in C, or have never coded in the C language before. This tutorial will attempt to guide you through some basics of the C language. After you read this, you should be able to code some simple programs in C with greater ease. Then from here my tutorials will get more advanced as we build from each one introducing the more sexy features of C.
----------------------------------------------
---C History---
Well what’s the use of coding in C (or any language) if you don’t know its history?!?!
C is a general-purpose programming language, which can be used to write almost anything including operating systems(with help of assembly). The Unix operating system actually gave birth to C, because C was developed to rewrite it. That’s why both the system and programs are usually always written in C on Unix and even Linux systems (the platform independent parts anyway).
In 1972 Dennis Ritchie at Bell Labs wrote the C programming Language from a major upgrade from the 'B' language. I never had the opportunity to code in the “B” language, but I’m sure it is just as satisfying ;P
The original C was quite good, but many programmers wanted a strict definition of the language so everything behaved in predictable ways. This is where ANSI C was born, which is the current C standard (C99). You can read more about this standard on Wikipedia. Also, this standard is defined in the second edition of the book “The C programming language”, by Kernighan and Ritchie (Creators of C, a MUST read!!!).
* Note the above book mention is usually shorted to “K&R” on IRC and forums.
Now C is a "Sexy" language, its syntax is elegant and the language itself has remained popular throughout the many years for it has been developed. The C language is also Platform independent meaning you can run a C program coded for an Intel x86 system (in some Cases) on a SPARC system if you take portability into account and use the correct system libraries with conditional compiling.
---------------------------------------------
Basic Differences between C and C++
Note: Thanks oib111 for prompting me to include this section
This short section will describe some subtle and major differences between C and C++. For beginners, the differences between these two languages will not be obvious, because you must learn the differences thoroughly to recognize and understand them. Since this part of the tutorial is the absolute basics, only the general differences will be discussed from a learning and usage standpoint. One good note for beginners is, that if you learn C you basically have learned half or more of C++! C++ is simply an extension of C with OOP(Object oriented programming) concepts. I’m not really going into how to code with object oriented design, because whole books have been written on it that describe it way better than I can. However, the basics of OOP are that it treats everything as an object. Objects are basically software engineering renderings of real world objects. Also, C++ offers something called “Classes” which promote software reuse for future programs to develop faster.
One major obvious difference is that C is a lot older than C++, it simply has been around longer and more software has been written in it.
Programming in C you usually divide your program up into functions. The C programming language was designed to code with procedural design, which is a fancy way of saying you use a lot of functions to simplify the layout of your program and make execution more efficient. However, with C++ you have classes instead of functions (although functions still are used) classes offer the ability to be reused in a lot of different programs due to OOP concepts such as encapsulation and abstraction.
Other major differences can’t really be discussed at this point without really confusing the hell out of you. So in on going tutorials I will introduce these differences when the time is right. However, generally C++ does things in the background automatically compared to C, which in most cases results in easier coding, but harder debugging.
Just remember, if you don’t know if you want to code in C++ or C, just learn C! It will give you a great programming background, and you will be learning most of what C++ has to offer at the same time! You just need to learn OOP and the more advanced features of C++ just as constructors and destructors, overloaded operators, inline functions, classes, etc… it is not a lost cause at all.
-----------------------------------------------
A note on the programming examples used in this tutorial
When you see blocks of code snippets sprinkled throughout this
Tutorial, they are meant to be used within the main() function, and
all required header files. I just post them that way here, because they
save space and concentrate on the concept at hand better.
-----------------------------------------------
What is Compiling?
Compiling:
You cannot directly execute your source file written in C. To run on any computer system, the source file must be translated into binary numbers understandable to the computer's CPU. These binary codes are the OPCODES for the CPU, and if you get the pleasure of learning assembly you will understand this better.
A C compiler takes your human readable C source code and translates it into machine-readable code (binary).
The compiler producers a object file which is the your C code in its binary form, then you run the linker which adds code from header files to your source to support such functions as printf and scanf. After your code has been linked an .exe (executable) file is made (or a.out or whatever your system uses natively)
---------------------------------------------
---preprocessor directives---
Preprocessor directives are commands for the compiler only and are ran before your program compiles. They instruct the compiler to do something with your source code, and begin with the symbol '#'. Some important preprocessor directives are #define and #include (which we will talk about later)
---------------------------------------------
Header Files
Header files are files that contain pre-coded library functions that you can add to your C program. You use the #include directive which instructs your compiler to add the contents of a header file in your program source. Header files are identified with the (.H) file extension.
For example:
Tells the C compiler to add the contents of stdio.h (standard input and output) to your C program to support such standard library functions as printf() and scanf(). One note I should point out here, using the < and > symbols tell the compiler to look in the compiler’s default “Include” directory. However, if you put the header file name in quotes such as this:
This will cause the compiler to look in the local directory where you program is being compiled in.
------Free C compilers------
Some good free Compilers are
G++
GCC (comes with most Linux distro's) What is with Ubuntu ?
LCC (Win32 C compiler)
Visual C++ 2005 express edition
Bloodshed's Dev-C++ (also can compile C code) www.bloodshed.net
If you have a favorite free compiler not listed, just post it as a reply to this tutorial!
-------------------------------------------------
---Commenting your source code---
Commenting is a way to describe what your program is doing, and what certain parts are doing or are for. You should always comment your program's source to make it clear to other programmers who may read it, and clear to you when you need to make changes or update it!!!. Comments are completely ignored by the compiler and are not a part of the actual program; they are just there for you and other programmers that look at the source to make it clearer. Most beginners have the belief that commenting will increase the size of your C program’s executable. This is not true! Comments aren’t included in the source (remove debug code in release mode)
There are two ways to comment source code lines in C.
The double-slash // can be used to comment a single line for example... (This is a C++ convention, but ANSI C compilers support it)
| Code: |
float total; // This variable well store the total amount of money in dollars and cents
|
(we well talk about variables and such next)
There is also the /* And */
Which can comment multiple lines of text you begin with the /* and comment then end with the */ ,when your done commenting. Example:
| Code: |
/***************************************
This is my program – It hacks any game ever made!
Bow down to the force!
****************************************/
|
-------------------------------------------------
---- C statements or aka "logical lines"----
A statement is a line of a C command instructing the computer to carry out some task. In C, statements are usually written one per line; C statements always end with a semicolon
(except for preprocessor directives such as #define and #include). A statement tells the computer to do something with data. For example:
| Code: |
int sum = 0; // Declare an integer called “sum” and assign it the value zero
sum = sum + 1; // Add one to sum (this will be explained later)
|
-------------------------------------------------
This may be a good point to say that commenting is good, but don’t over-comment. Yes, you can over comment, if you comment your programs like I have done above it will be a nearly wasted effort. The reason why I comment so much in this tutorial is because of teaching reasons. Only comment on peculiar statements, and custom functions in which a programmer or yourself will forget or not understand why you coded it the way you did. Programmers know that you are trying to declare an integer above, but if you’re declaring it to hold a non-integer value such as a character value. Then you may comment that tidbit of information in. (Please do! )
----The main() function, and brief notes on functions---
A function is a block of code that only executes when it is called, and can return a value. They are coded to perform a strictly defined task, they don't try to accomplish everything, they are coded to do a specific job. For example one function could be made just to get and process input from the user, and do nothing more(It would pass it to another function to do another task).
what are the { and } for?
{ and } are for block statements of code, they make up the body of our program and define things called “functions” and other things which we will learn in tutorials to come. They basically are a notation to mean that multiple lines of code belong to the particular function associated with them. Note this is when a function is declared and not called. A basic example on how to declare functions is:
return_type Function_Name(comma separated parameter list)
return_type is a C type the function will return to the calling code(Usually stored in a variable)
FunctionName is the name of our function.
Now what are parameters?
Parameters are basically variables See section on variables below that act as local storage places to store passed values to our function called "arguments".
| Code: |
int my_function(int x, int z)
{
// Insert function code here
}
|
Don't worry, I will discuss functions a lot more and in detail in part 2 of this tutorial.
-------------------------------------------------
With that said, the main() function is called automatically, it is the first function called and every C program needs a main function, the () are used to accept arguments (which we will discuss in Part 2 of this tutorial)
(Arguments are the variables to be passed to the function)
Below will show the basic layout of a simple C program, Just waiting for code
| Code: |
#include <stdio.h> //Include header file stdio.h in our program
/* Below Declares the main function main() and the int is to tell the compiler that it well return a integer(whole number) value, the value in this case is (0) this is returned to the operating system to check error status*/
int main()
{
// Code goes between the { and } (above the return 0; statement also)
/* The statement: return (0); below, Exits our program, And function main() returns the value of (0) to the operating system, telling it, our program has ended normally */
return (0);
}
|
-------------------------------------------------
---Variables, types, and constants---
When you want to store something for later use in your C program or perform a calculation and keep the value what do you do?
We need to declare a variable, what is a variable you may ask? A variable is a named storage location in your computers memory (RAM) that can change as the program is running. So when you use a variable we are actually using some address storage locations in your computers memory. The compiler actually keeps a table of variable names associated with memory addresses that is uses for translation. Variable names are much more human friendly to work with than hex memory address notations.
As stated the value stored in a variable can change as your program is running, so you can re-assign it a different value if you wanted to.
NOTE: It it always good practice to initialize your variables with some value, usually a starting value, or zero.
A constant is the same thing as a variable, but with one difference, the value cannot change while the program is running hence (constant).
Like a variable, a constant is a data storage location used by your program. Unlike a variable, the value stored in a constant can't be changed during program execution. C has two types of constants:
Note: Constants are assigned to variables! This refers to numerical symbols, and letters used in strings of characters.
-------------------------------------------------
Literal Constants
A literal constant is a static value that is used in the source code of your program along with the instructions. They are often referred to as "Magic Numbers", and take the form of numerical numbers, symbols, letters...
| Code: |
int count = 20; // Variable being assigned a literal constant with the literal value of 20
|
Note that a literal constant is stored in a variable! What the heck?, well the term literal constant refers to a fixed value used in statements. “20” will never change; it is static and put directly into the source code of the program. In this case it doesn’t refer to the way it is actually stored. Literal constants refer to fixed data that can be assigned to variables.
-------------------------------------------------
Symbolic constants
A symbolic constant is a type of constant that is represented by a name (symbol) in your program. You can think of this as constants in mathematics, such as the constant "e" or "pi" we use those symbols to represent the actual values.
This will create a constant variable that has a fixed value stored in it. Trying to change the value of a constant variable when the program is running will result in a compiler error!
C has two methods for defining a symbolic constant: the #define directive and the const keyword.
#define directive is used as follows:
| Code: |
#define CONSTANTNAME literalvalue
|
This creates a constant named CONSTANTNAME with the value of what ever literal you defined. It is customary that you adopt a popular time tested practice of using uppercase letters for your constants, and lower case or camel(VarName) notation for variables.
For the previous example, the required #define directive would be:
| Code: |
// this creates a symbolic constant named (PI) with a literal value of 3.14
// Acknowledge NO semi-colon for #define as described earlier
#define PI 3.14
|
We can also use const as follows
const type CONSTNAME value;
example:
| Code: |
//This creates a symbolic constant of type Float, named PI, with the literal value of 3.14
const float PI 3.14;
|
-------------------------------------------------
Constants are very useful you can declare them at the top of your program and if you need to change their value in an updated version of your program, you can do it very easily. Take this following example.
Say we made a program that needed the value of pi, and we didn’t want to keep "plugging" it in all over the program, also called "magic numbers"
we can use a constant
We would use that on the top of our program above the main() function near the #include directives, and to use its value we just type in PI.
Say three months later we want PI to be more precise for certain calculations, well all we do is change the constant PI and the whole program is updated!!!. Example:
| Code: |
#define PI 3.14159265
|
The compiler will replace anywhere, where the constant “PI” is used in an expression to the new value before you program is recompiled.
-------------------------------------------------
Naming Variables
-------------------------------------------------
Important NOTE: C is a Case sensitive Programming Language, What does this mean?
C treats upper and lower case characters differently
So (X) is not the same as (x), they are completely Unique Names for variables!
This goes for everything in C, Even Commands! Printfis not the same as printfand will most likely cause a compiler error! (A common mistake)
-------------------------------------------------
Variables should be named after what they are storing to make the name and intentions clear, Avoid the names like xgh, kj2, uuytd, etc.....
Some rules you must follow when naming variables are:
Variable names must begin with either a _ or a LETTER
(they can’t begin with a symbol, number, or special character)
Variable names can’t contain any spaces or special characters other than _
Also, Variables CANNOT have the same name as commands in C (Reserved Words), Search google or your compiler help file for a list of Reserved words.
Some examples are..
| Code: |
int 8total; // ILLEGAL!!!!!! (starts with number)
int total; // LEGAL
int _total; // LEGAL
int _total_amount; // LEGAL
int total amount; // ILLEGAL!!!!! (has a space)
int total&amount; // ILLEGAL!!!!! (has a special character (&) )
|
---------------------------------------------------------
-How do I declare a variable?-
Declaring a variable is easy: type varname;
Type defines what Type of value we will be storing in the variable, these are the most common:
Numeric Variable Type in C
C's numeric variables fall into the following two main categories:
Integer variables hold values that have no fractional part(whole numbers only). Integer variables come in two flavors: signed integer variables can hold positive or negative values, whereas unsigned integer variables can hold only positive values (Including 0).
Floating-point variables hold values that have a fractional part (decimals).
-------------------------------------------------
The first type of variable we need to know about is of type int – (short for integer). An int variable can store a value in the range -32768 to +32767. We CANT store a Decimal!
To declare a variable of type int we use this instruction:
| Code: |
int menu_choice; // Declares Variable named menu_choice of type int(integer)
|
Note: How did I get this range? Well, the size of C data types varies from system architecture to system architecture. The real sizes for your system are defined in the limits.h header file (Take a look with your favorite text editor!). For my system, an integer type is 2 bytes by default. Now if you know binary, a byte can hold 256 different values. This is calculated from 2^8, which is 2 to the 8 th power. Why use 2 for a base? Well, memory locations can only hold two values, a zero or a one.
So for a 2 byte value, this can hold 2^16 values, or 65,536 different values. Now note this is only for positive values! Since, we didn’t declare our integer as an unsigned variable (explained below). Basically doing:
| Code: |
unsigned int blah = 0;
|
Tells the compiler we only intend to store positive values in our integer. Important: by default any variable not explicitly declared with the unsigned keyword is signed!
So by default:
This declares a signed variable that can hold negative and positive values. Now since we intend to store negative values it cuts our positive range a little less than half of it’s unsigned range. You should know about the two-complement system on the Intel architecture (Consider that a reading assignment for tonight ;P)
Basically the positive range of a signed variable is found by the formula: 2^(n-1) –1
Where n is equal to the number of bits in the variable. We go down a power because of the way the two-complement system works. So with our 2 byte signed integer our positive range is: 2^(16-1) – 1, so 2^15 = 32768, and we subtract one again because of zero! So the positive range is really 32767, and the negative range is 2^(16-1) or 32768. Notice the negative range is one higher due to no zero space.
Quick note on integer types short and long
You can use the “short” and “long” keywords before “int” in your integer declarations to cause the compiler to use a smaller or bigger version of the integer (most of the time). Example:
| Code: |
short int small = 789;
long int big = 234987;
|
Most of the time the “short” keyword causes a 2 byte int to be defined, and the “long” keyword causes a 4 byte int to be declared. One or the other is default for your compiler, and the size of these types is system dependent.
Note: ANSI C allows you to just declare a type “long” instead of using “long int” and C guarantees a long integer to be ATLEAST the size of a normal integer.
You can gain even more range by declaring an unsigned long which can hold a value of about 4 billion!
-------------------------------------------------
Other types are:
float - floating point value: is a number with a fractional part.
A float, or floating point, number has about seven digits of precision and a range of about 1.E-36 to 1.E+36. A float takes four bytes to store in RAM on most systems.
-------------------------------------------------
double - a double-precision floating point value.
A double, or double precision, number has about 13 digits of precision and a range of about 1.E-303 to 1.E+303. A double takes eight bytes to store.
-------------------------------------------------
-A NOTE on characters-
char - a single character.
To assign, or store, a character value in a char data type is easy - a character variable is just a symbol enclosed by single quotes. For example, you can store the letter A in the temp variable below using the following C statement:
| Code: |
char temp;
temp='A';
|
*NOTE it is a good place to point out that you can reduce this to one line. In C you can assign values when you declare a variable of any type, such as:
*NOTE: Character constants are always used with single quotes such as ‘A’, and string constants are in double quotes, such as “omg”. This is because the C compiler has to add a special character at the end of string constants called a NUL character, and it needs a way to determine if you intend to use the constant as a character or string.
A character declared that way can only store a single character, What if we want strings?
Now some interesting things about the char data type is that we can construct strings from it using a character array such as:
*NOTE: If you don’t understand what an array is yet, I will discuss them fully in the second part of this tutorial including pointers!
| Code: |
char temp[7] = "Hacker";
|
The character array, temp, above can store 7 characters, 0 to 6, Remember this that C always starts counting from 0.
So why declare a character variable that holds 7 characters while you are only storing 6 "Hacker"?
We have the extra amount of storage for a very important reason, the extra storage is for the string null terminator (\0), which is added automatically and occupies one byte. The null terminator tells C when the string ends so it can go on to the next line of code. So learning this you should always declare a character array one more byte higher than you need.
So if you need to declare a character array that needs to store a 10 char string, you need to declare it to store 11 to account for the null terminator.
For Now, Do not store a string in the character or character array that is bigger than it is declared!, You well get a Nasty Overflow error and Unpredictable Results!
Part 2 of my Tutorial well show you how to use some protection to make sure a user doesn’t enter in text to large to store in your character array!
We well talk a lot more in detail on Characters and Character String in Part 2 of my tutorial.
-------------------------------------------------
---Operators---
The assignment operator is the equal sign (=).
x = y;
This may look a lot like in math class where you see an algebraic equation and it means “x” is exactly equal to “y”. In C this isn’t the case, it means you are assigning the value of “y” to the variable “x”. For example:
| Code: |
int blah = 0; // Declare an integer named blah and assign the value zero
blah = 1337; // assign the value 1337 to variable blah.
|
Note: other operators will be discussed in part 2 of this tutorial including relational and bit wise operators.
-------------------------------------------------
Mathematical Operators
I hope you took math class and know these... ;P
| Code: |
-------------------------------------------------
+ - Addition, example, x = 2 + 2; // variable x will have the value of: 4 (2 + 2)
- = substraction example, x = 6 - 3; // variable x will have the value of: 3 (6 - 3)
/ - regular division example, x = 8 / 4; variable x will have the value of: 2 (8 / 4)
* - multiplication example, x = 9 * 5; variable x will have the value of: 45 (9 * 5)
% - modulus division (returns the remainder) example. x = 9 % 2; variable x will have the value of: 1 (9 mod(%) 2 = 1)
|
-------------------------------------------------
Now the order of operation evaluation- this simply means that C follows a strict way of evaluating mathematical expressions.
| Code: |
take the expression: x = (7 + 8) - 2;
|
C would evaluate it as follows:
first it would do what’s in parentheses: 7 + 8 then it would subtract two from that value so:
7 + 8 = 15
then
15 - 2 = 13
so x would equal 13
why?, its basic algebra remember the phrase "PEMDAS" from school? the order of operations
PEMDAS is the sequence C evaluates any mathematical expression
P = parentheses ()
E = Exponent E^2 IS WRONG! The ^ operator doesn’t mean exponentiation in C!!!!!
M = Multiplication *
D = Division /
A = Addition +
S = Subtraction -
Some notes on division and basic type casting
Division is a very peculiar thing with computers, just like in mathematics division by zero is not defined, but on computers the operation could be fatal. However, modern processors protect the system from going down from a zero division error so you could breathe a slight sigh of relief. Also, most modern compilers will generate compiler errors preventing you from running the program until you fix the divide by zero problems.
C type division o.0
The C programming language seems to have its’ own way of doing things when in comes to division. C does certain things automatically and by default which could really slip up beginners (I know when I started out it made me freak out once). These things are the difference between what C calls integer division and floating-point division. C determines the type of division to use based upon the types of the operands (variables) used in the division.
Before I discuss how this works, lets briefly define the difference between the two. As you may recall integers cannot hold fractional (decimal) values. So the when you divide two integers the remainder is truncated (not used) or stored.
Example:
| Code: |
int value1 = 7;
int value2 = 3;
int result = value1 / value2; // Notice division is / not \
|
So what value will C store in the variable “result”? Since both variables used in the division are integers, C by default performs integer division. So the result will be: 2
The remainder (1) cannot be stored because it is a fractional part: 2.33333….
It is a good place to point out that floating-point values are stored specifically on the Intel architecture explaining why they need more space and special operations. If you are ever bored search Wikipedia for floating point values.
So then, how do we get C to trigger a floating point division in a calculation?
The easiest way is to use either floating-point variables in the division, use one floating-point value in the division, or use a type cast. Acknowledge!!!, if you are storing the value in a variable the variable must be a float if you are using floating-point division!!! Otherwise, the result will be lost anyway because it is being stored in an integer variable, also remember to use %f in printf() and scanf() for float values.
The disadvantage for the first option is that using floating-point variables when they aren’t specifically needed is a waste of memory space.
The second option of using one floating-point value in the division, may be practical:
| Code: |
float value1 = 7; // You can use either 7 or 7.0 since it is a float
int value2 = 3;
float result = value1 / value2; // NOTICE: division is being assigned to a float variable
|
The variable “result” will have the value 2.3333 stored in it, so the floating-point division worked!
Our third option of Type Casting requires some explanation.
Note: Typing casting in itself is quite “advanced”, in that some things are handled automatically, so it’s best to read a formal book that explains all these. I suggest K&R Second Edition, in fact I highly recommend you read it if you want to really know C!!!
Type casting basically temporary alters the variable during an operation so it behaves as another variable type. It doesn’t do it permanently unless you store that value in another variable.
To make a type cast you use the type name you want to type cast as between a pair of parenthesis before an expression or variable.
Basic Example:
| Code: |
printf("\nYou entered the value: %f \n\n", (float)7/3);
|
Notice normally an integer division would have occurred. This brings up another tidbit of the conundrum known as C:
If you are dividing a variable by a constant such as this varname / 2
You can use this: varname / 2.0, by using a decimal point on the constant, you are telling c to use automatic float type casting.
-----------------------------------------------------------
So it will look if there’s any parentheses, if there is it will evaluate that first, if there isn’t, then it will move on to Exponents and etc.... following the sequence of "PEMDAS"
Speaking of exponents, how do we use them in C if the ^ operator doesn’t mean exponentiation?
The simplest solution is to #include <math.h> in your program. Then use the pow() function.
*NOTE: We will be discussing functions in more detail in part 2 of this tutorial
Example:
| Code: |
//Note always include all your header files and constants at the file top of the program source file
#include <math.h>
int main()
{
int Base = 2;
int exp = 3;
int result = pow(Base, exp);
return 0;
}
|
The pow function takes the first argument (Base), and multiplies it by the second argument (exp). Hence, calculating the exponentiation and storing it in the result variable.
You may be noticing that we need a way to see what is stored in our variables. This is explained in the next section. I will introduce the most basic input and output functions in this tutorial, and then explain how to better get input and also talk about security in the second tutorial.
-------------------------------------------------
- BASIC INPUT AND OUTPUT-
well its not a program without any output to the screen or input from a user to the program is it?
The following functions we are going to use (printf and scanf) require the stdio.h header file
Printing a text message in the console window is simple. Call the printf() function, passing the message you want to output enclosed in double quotation marks(for a string)
Example to print the message I Love to Hack, Enter the following:
| Code: |
printf("I Love to Hack"); // Simple eh?
|
Now for a bit more advanced use of the printf function:
Just displaying Pre-defined text strings is cool, but you frequently need to display the value of program variables.
Say we wanted to print the value of a integer variable named x, how would we do it?
| Code: |
printf("\nThe value of x is %d", x); // lets discuss this below
|
The above example has two arguments that are passed to printf(). The first argument is in double quotation marks and is called the format string The second argument is the name of the variable (x) containing the value to be printed. Notice this can be a list of variables separated by commas, but you need a type specifier in the format string for each variable!!!!
The format string in the printf() statement describes what and how our string of data will be displayed on the screen. The format string consists of things known as the actual text and escape sequences and format specifiers.
The text, This is what is inside the " and ", But it doesn’t print the %d, the corresponding variable will replace the format specifier in the format string(discussed later).
Another component of the format string in the printf function is called an escape sequence. This component provides certain formatting control of the text being printed. To specify an escape sequence, you use a backslash “\” followed by a single letter. For example, we have used “\n” a couple times already in this tutorial. This escape character is called the newline character, and it makes text to be printed on a new separate line. Some useful escape sequences are listed below:
-------------------------------------------------
| Code: |
\a Bell (alert beep)
\r Carriage Return
\b Backspace
\n Newline (Moves to the start of the next line)
\t Horizontal tab (Inserts tab)
\\ Backslash (Inserts a backslash in the text)
\? Question mark (Inserts a ? in the text)
\' Single quotation (Inserts an ' in the text)
\" double quotation (Inserts an " in the text to quote)
|
You may notice you have to use \" to use double quotes in the format string, why? Because the format string itself is enclosed in double quotes, and the compiler would get confused if you just used the double quotes, which it may take as ending and beginning multiple format strings(Which there is only one format string per printf statement.
-------------------------------------------------
The printf() Conversion Specifiers
The format strings of such functions as printf and scanf (discussed later) are very special. In the format string you can place special sequences called Conversion Specifiers . Conversion specifiers dictate how a variable is displayed on the screen numerically or if it’s say an ASCII character. More importantly, by placing a conversion specifier in the format string it takes the place of a variable in the variable list of the printf statement. Again, this is how the printf statement looks:
| Code: |
printf(“\n\nI’m the format string %d %d %f”, var1, var2, var3);
|
Notice the format string is in quotes, and has three conversion specifiers. Also, notice that there is a comma after the list then three variables. The comma separated variables are known as the variable list, and each variable has to be in the correct order with it’s intended conversion specifier. For the above example:
The first %d in the format string is replaced with the value in var1
The second %d in the format string is replaced with the value in var2
The third conversion specifier of %f is replaced with the value in var3
The printf() function stores it's passed variables on something called the "stack" which we will talk about in later tutorials.
IMPORTANT: If you don’t have the correct number of variables for each conversion specifier the program will display junk because it’s getting that junk value from memory (the stack).
Also, you need to use the correct conversion specifier for the kind of value in the variable it will be replaced by. For example, if you used a %d (decimal integer) conversion specifier to print a float variable it would truncate the value to a whole number only. Actually it would most likely crash your program in most situations, because each conversion specifier grabs a certain amount of data off of the stack(the size of the intended variable type).
Of course the concept of using conversion specifiers to represent data differently is very useful. In C, certain notations are established to represent common bases of numbers (decimal, octal, hex) for example:
| Code: |
Any number constant with a 0x is considered a hex value for example: 0xDEAD123
Any number that begins with a 0 (number zero) is considered octal, for example: 083
Any other number is decimal
|
Say however, you wanted to make a quick and dirty way of converting a decimal value to a hex value. You can exploit the conversion specifer power of the printf() function to do this! Remember conversion specifers are used to tell printf how to display the value of a variable it is replaced by.
For example:
| Code: |
int foo = 16;
// Lets display the value in the variable foo (holding a decimal integer value of 16) as hex
printf(“\n The decimal value %d is %x in hex!!!\n\n”, foo, foo);
|
Notice we used the variable “foo” twice in the variable list, but observe the difference in conversion specifers. This will indeed print the value in foo differently!
There are many more things you can do with conversion specifers, I highly suggest reading about them in K&R or an online reference.
The most common format specifers are listed below:
-------------------------------------------------
| Code: |
%c Single character, variable type: char
%x - hexadecimal value
%o - octal value
%d Signed decimal integer, variable type: int, short
%ld Signed long decimal integer, variable type: long
%f Decimal floating-point number, variable type: float, double
%s Character string, variable type: character arrays
%u Unsigned decimal integer, variable type: unsigned int, unsigned short
%lu Unsigned long decimal integer, variable type: unsigned long
|
-------------------------------------------------
What about printing the values of more than one variable?
As you already saw you can use more than one conversion specifier in a format string. Also, theoretically the printf() function can use any number of variables in the variable list as long as you have the stack space in memory. Also, please remember you need to match the conversion specifers with each variable, and have the correct number!
Example:
| Code: |
float time = 900.5; // measured in milliseconds
int damage = 90;
printf("Time = %f, Damage = %d", time, damage);
|
Notice there is a comma after the format string where the variables start. You can't put the variables in the format string because it will display the actual text of: ( , time, damage) which we don't want. The variables need to be separated by a comma from the format string, and their values are replaced by position with each format specifier location.
Our variable, time is used with the %f specifier, and our variable damage us used with the %d specifier. The values of the variables actually replace the specifiers in the format string to print the variable values we need.
Note: There is an alternative function available in the stdio.h header file that is for just printing strings to the screen. This function is called puts() and can only print strings with no variables, also it adds a newline escape sequence automatically after the printed string.
| Code: |
puts("This program was coded by me!");
|
As you can see it's useful for printing prompts and titles and things that don't need to display variable values.
--------------------------------------------------
INPUT and the scanf() function[B]
[B]Remember, scanf() needs the stdio.h header file, as printf() does also
The scanf() function reads typed data from the keyboard. The type of data scanf() reads is determined by conversion specifiers, and it also stores the data into multiple variables passed to it. The scanf function isn't really reliable and used in mainstream programming much, and I will explain this better in part 2.
The format string has the same conversion specifies as the printf() function. For example, the statement:
| Code: |
int x = 0; //Initial value of x is zero
scanf("%d", &x); // store user entered value in x
|
Reads a decimal integer from the keyboard and assigns it to the integer variable x.
Another Example:
This statement reads a floating-point value from the keyboard and assigns it to the variable rate:
| Code: |
float rate = 0;
scanf("%f", &rate);
|
Notice that the conversion specifier used in the format string in the scanf() statement determines what the scanf function expects to read from the user, and how it is stored in the variable.
In case you were wondering, yes you can use multiple conversion specifiers in the format string of scanf just like printf. This is used to read multiple values and store them in multiple variables on one line of input. This is were the usage of scanf gets unreliable and shady, take this example:
| Code: |
float omg = 0;
int wtf = 0;
puts("Enter in a float value then a decimal value seperated by a space");
scanf("%f %d", &omg, &wtf);
|
Notice it has the exact same setup as the printf statement. %f is used to read a float value and store it in "omg", and %d is used to read an integer value and store it in "wtf". Notice there is a space between the two conversion specifiers in the format string. This is how scanf delimits(Or recognizes how to determine when each value begins and ends). This gets fairly shady, and is quite involved in some cases, so best thing is to read about it in K&R or an online reference.
Also, notice that the conversion specifiers must be correct, you can't tell scanf to use %f to store a value in an integer. In some cases it will work anyway(with just the value truncated as a whole number), but in other systems it will crash the program because a float is larger than an integer!
What is the ampersand (&) before the variable's name?
The & symbol is C's address-of operator, Which we well discuss in PART 2 of my tutorial, in the section "POINTERS".
So until you understand functions and pointers a lot better, remember to include the & operator before each variable in the scanf variable list. This is where a lot of beginners get confused, because you need to understand pointers and memory addresses.
----------------------------------------------------------------------------------------
A look into Part 2
Part 2 of this tutorial well include:
Functions
Arrays
Better I/O
Logic operators
If statements
Loops
pointers
string manipulation
And More!
----------------------------------------------------------------------------------------
If your program suddenly quits or never displays anything
This is a result of windows XP closing the command console in which your program is run. This problem can be solved by including the stdlib.h header file. Then using this command before the main() function returns:
That will send the system dependent DOS command PAUSE that will close the console window only when you hit the enter button.
-------------------------------------------------------------------------------------------
A complete basic example of program
This contains helpful comments in it to try to pull these concepts together. Also you can use this as a template for your programs while you learn.
| Code: |
/**********************************************************************
Complete Basic example program that takes the value a user enters
then tells them what they entered. I know simple ;P lol
// BTW this is known as a comment block and should describe what the
//programs purpose is. Like I did above
// Also try to include this information:
AUTHOR: NigTronIX // The author's name
DATE LAST MODIFIED: June 2nd, 20007
EMAIL [email protected] // Include contact information
TODO: // Make a TODO list of things you want to add or change in the future
// Also with big programs include a seperate text file that lists changes
// This is called a "changelog"
// Also you may want to release your program under the GPL
// Use Wikipedia to find out more about the General Public License(GPL)
***********************************************************************/
/* INCLUDES */
#include <stdio.h>
#include <stdlib.h> // Use this with system("PAUSE"); if you can't see what your program displays
/* CONSTANTS */
// None ;{
int main()
{
int UserValue = 0; // Notice I assigned this to zero, and notice the captial letters(THESE MATTER!)
// Notice the intial \n (newline) this is to make sure we are printing on a seperate line
// Notice there is no \n at the end this so the user's typed value is on the same line as our prompt
printf("\nEnter a value for me to see!: ");
scanf("%d", &UserValue); // notice we are using %d cause UserValue is an integer
// Also notice C is indeed a Case Sensitive language, our variable is UserValue not uservalue!!!
// Acknowlege we need to add error checking to this program and security but that is discussed later
// Now that we have our value (Hopefully) we can now use it, in this case print it to the screen
printf("\nYou entered the value: %d \n\n", UserValue);
system("PAUSE"); // Used to keep the console window open
return 0; // Send 0 to the OS telling it our program ended normally, Yes zero means normal, anything
// greater than zero means an error, with 1 being the minor error
}
|
--------------------------------------------
Programming exercises for part1:
Exercise 1.1:
Write a program to print your name and age on a single line.
Exercise 1.2:
Write a program that inputs an integer from the user then calculates the square of the number prints the result.
Exercise 1.3:
Write a program that calculates how much you will be paid each week, by the user entering in the hours you worked, and your pay rate. If you feel really ambitious, add in tax deductions and other features.
Where to go from here
This tutorial, and my potential future tutorials will not teach you much as books on programming. I made this tutorial to get you familar with C and to possibly spark your interest. Below is my personal list of books that I have bought and read, and can actually recommend as supplement reading:
Always remember never just read, CODE, CODE, CODE, CODE, CODE!
The C Programming Language (2nd Edition) * A MUST READ
http://www.amazon.com/C-Programming-Language-2nd/dp/0131103628/ref=pd_bbs_2/103-0273993-6960657?ie=UTF8&s=books&qid=1181421457&sr=1-2
Practical C Programming, 3rd Edition * A great book on programming in C
http://www.amazon.com/Practical-Programming-3rd-Steve-Oualline/dp/1565923065/ref=pd_bbs_2/103-0273993-6960657?ie=UTF8&s=books&qid=1181421531&sr=1-2
C primer Plus, 5th edition by Stephen parta *Great general course to clearify some things
http://www.amazon.com/Primer-Plus-5th-Stephen-Prata/dp/0672326965/ref=sr_1_7/103-0273993-6960657?ie=UTF8&s=books&qid=1181421644&sr=1-7
Secure Coding: Principles and Practices by Mark Graff
*Very Good book once you know how to program. General introduction to software security
http://www.amazon.com/Secure-Coding-Principles-Mark-Graff/dp/0596002424/ref=pd_sim_b_3_img/103-0273993-6960657?ie=UTF8&qid=1181421644&sr=1-10
Secure Programming Cookbook for C and C++ by John Viega
*Very nice collection of information, A must read if you are distributing software
http://www.amazon.com/Secure-Programming-Cookbook-C%2B%2B-Authentication/dp/0596003943/ref=pd_sim_b_1_img/103-0273993-6960657?ie=UTF8&qid=1181421644&sr=1-10
Programming Windows, Fifth Edition by Charles Petzold <3, Charles you rock!
*The book is a little dated, but it is very well written, and excellent for a win32 beginner
http://www.amazon.com/Programming-Windows-Fifth-Charles-Petzold/dp/157231995X/ref=sr_1_2/103-0273993-6960657?ie=UTF8&s=books&qid=1181422122&sr=1-2
The Practice of Programming by Brian Kernighan and Rob Pike
*THis book is fooking awesome, plus it's written by the co-author of k&R
http://www.amazon.com/Practice-Programming-Brian-W-Kernighan/dp/020161586X/ref=pd_bbs_sr_1/103-0273993-6960657?ie=UTF8&s=books&qid=1181422352&sr=1-1
Current book I'm reading: Mastering Algorithms in C by kyle Loudon
*This book is a little more advanced, and it is mathematically oriented, but I love it so far
http://www.amazon.com/Mastering-Algorithms-C-Kyle-Loudon/dp/1565924533/ref=pd_bbs_sr_1/103-0273993-6960657?ie=UTF8&s=books&qid=1181422236&sr=1-1
If you see any errors in this tutorial, post it as a reply to this tutorial. Thank you for reading Part1 of my C programming series, Part 2 will be coming up pretty soon as well.
Last edited by Nigtronix on Sat Jun 09, 2007 2:08 pm; edited 19 times in total |
|
| Back to top |
|
 |
Flyte Peanuts!!!!
Reputation: 6
Joined: 19 Apr 2006 Posts: 1887 Location: Canada
|
Posted: Fri Jun 01, 2007 8:15 pm Post subject: |
|
|
| Sticky this. Nice job. |
|
| Back to top |
|
 |
appalsap Moderator
Reputation: 0
Joined: 27 Apr 2006 Posts: 6753 Location: Pakistan
|
Posted: Fri Jun 01, 2007 8:22 pm Post subject: |
|
|
| I googled some excerpts and some came up word-for-word in various C books like "teach yourself C in 21 days" but if you really wrote this yourself it's a pretty good tutorial. |
|
| Back to top |
|
 |
benlue Moderator
Reputation: 0
Joined: 09 Oct 2006 Posts: 2142
|
Posted: Fri Jun 01, 2007 8:25 pm Post subject: |
|
|
| Was this just taken from lots of C books and put together ? |
|
| Back to top |
|
 |
Nigtronix Cheater
Reputation: 0
Joined: 18 May 2007 Posts: 45
|
Posted: Fri Jun 01, 2007 8:26 pm Post subject: |
|
|
Thanks , Yes I did write this myself, the only part I took out of a book was the printf type specifier list and escape sequence list which is reference material anyway. |
|
| Back to top |
|
 |
--Pillboi-- Grandmaster Cheater Supreme
Reputation: 0
Joined: 06 Mar 2007 Posts: 1383 Location: I don't understand the question. Is this a 1 to 10 thing?
|
Posted: Sat Jun 02, 2007 3:05 am Post subject: |
|
|
This is very nice. I've been trying to learn. Thanks. Can't wait for the next one! +Rep _________________
Enter darkness, leave the light, Here be nightmare, here be fright...
Earth and Water, Fire and Air. Prepare to meet a creature rare.
Enter now if you dare, Enter now the dragon's lair. |
|
| Back to top |
|
 |
oib111 I post too much
Reputation: 0
Joined: 02 Apr 2007 Posts: 2947 Location: you wanna know why?
|
Posted: Sat Jun 02, 2007 3:37 pm Post subject: |
|
|
GJ, I mean seriously, I was taking C++ tutorial, but it isn't half as good as your part one. And um, just checking, C and C++ are almost the same, just C++ has some more functions, the person teaching didn't really get into their similarity much. Btw +rep! _________________
| 8D wrote: |
cigs dont make people high, which weed does, which causes them to do bad stuff. like killing |
|
|
| Back to top |
|
 |
TheSorc3r3r I post too much
Reputation: 0
Joined: 06 Sep 2006 Posts: 2404
|
Posted: Sat Jun 02, 2007 8:03 pm Post subject: |
|
|
Is this open to Q&A? Because I'm gonna ask anyway
You can dereference a pointer which contains a memory address (a dword), but you can't dereference a dword itself. Why?
Ex:
| Code: | int j = 5;
int *ptr = &j; // ptr holds the address of j which is a dword
*ptr = 7; // That address (dword) is being dereferenced
// That was all legal |
| Code: | dword dw = 0x00666666; // dw holds the address 0x00666666
// another dword
*dw = 7; // That dword (address) is being dereferencd
// This isn't legal. Why? |
Also, what's the point of a dword pointer? Wouldn't a normal dword do the same job?
Appal: I asked you about this before (maybe I mislead you with my problem), and you said it was printf()'s fault. It wasn't. _________________
Don't laugh, I'm still learning photoshop! |
|
| Back to top |
|
 |
DeltaFlyer Grandmaster Cheater
Reputation: 0
Joined: 22 Jul 2006 Posts: 666
|
Posted: Sat Jun 02, 2007 8:51 pm Post subject: |
|
|
| TheSorc3r3r wrote: | Is this open to Q&A? Because I'm gonna ask anyway
You can dereference a pointer which contains a memory address (a dword), but you can't dereference a dword itself. Why?
|
Well, a dword isn't a pointer. If the complier lets you dereference a dword, what would the data type of the value be? There would be no data type specified.
You could tell the compiler what kind of data to expect at the address by casting the dword into the respective pointer. Ex:
| Code: |
DWORD iPtr = 0x12345678;
*((int*)iPtr)=2;
|
| TheSorc3r3r wrote: |
Also, what's the point of a dword pointer? Wouldn't a normal dword do the same job? |
One use is in functions. For example you have a function that would return multiple dword values. One way to do this is to pass in all the dword pointers, then let the function edit the values. After the function returns, the caller will be able to get the returned dword values by accessing them from the pointers.
It appears quite often in.... everywhere. _________________
Wow.... still working at 827... what's INCA thinking?
zomg l33t hax at this place (IE only). Over 150 people have used it, what are YOU waiting for? |
|
| Back to top |
|
 |
Nigtronix Cheater
Reputation: 0
Joined: 18 May 2007 Posts: 45
|
Posted: Sat Jun 02, 2007 10:33 pm Post subject: |
|
|
Wow thanks guys, by the way I added some new sections:
Basic differences between C and C++, Notes on division in C, an example of a full simple program in C, and a few programming exercises. |
|
| Back to top |
|
 |
VexingCode How do I cheat?
Reputation: 0
Joined: 18 May 2007 Posts: 1
|
Posted: Sat Jun 09, 2007 1:40 pm Post subject: |
|
|
| Wow Nice Tutorial, Extremely helpful *Sticky*, Can't wait for the next one |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You can download files in this forum
|
|