C category list
A Simple Piece of C Code
#include <stdio.h> int main() { /* my first program in C */ printf("Hello, World! \n"); return 0; }
#include <stdio.h>
The first line of the program is a preprocessor directive which tells a C compiler to include the contents of file stdio.h. Include files contain additional information used by the program file during compilation. Stdio.h file stands for standard input-output header file and contains various prototypes and macros to perform input or output (I/O)
Main Function
The main() function is where program execution begins and is required by every executable C program. Every function must include a pair of braces marking the beginning and end of the function. Within the braces are statements that make up the main body of the program
Program Comments
Any part of a program that starts with /* and ends with */ is called a comment and is ignored by the compiler. Programmers use comments to explain their code but do these not affect the running of the code
Printf Statement
The printf() statement is a library function used to display information on-screen. In the example above, printf outputs the contents of the quotation marks followed by a new line \n.
The Return Statement
All functions in C can return values. The main() function returns a value and in this instance, the value 0 indicates that the program has terminated normally. A nonzero value returned by the return statement tells the operating system that an error has occurred.
Semicolons
In C, the semicolon acts as a statement terminator and indicates to the parser where a statement ends. Several statements can be included on one line as long as each statement is terminated with a semicolon.
- Details
- Category: C category list
- Hits: 278
Variables are named locations in a computer's memory used to store data. The value of this variable can be changed one or more times during the execution of a program. In C, all variables and the type of values that the variable can hold must be declared before they are used and must adhere to the following rules:
- The variable name can contain letters (a to z and A to Z), digits (0 to 9), and the underscore character ( _ )
- The first character of the name must be a letter. or underscore. A digit cannot be used as the first character.
- C is case-sensitive.
- C keywords are not acceptable as variable names. A keyword is a word that is part of the C language.
Variable Declarations
A variable declaration will specify to the compiler the name and type of a variable. When a variable is declared the compiler automatically allocates memory for it and this size can vary depending on the computer platform. Any attempt to use a variable that hasn’t been declared will result in the compiler generating an error message. A variable declaration will consist of the variable type followed by the variable name. Multiple single-line variable declarations are possible by separating each variable name with a comma –
int x //declares variable of type int float x,y,z; //declares variables of type float short int x,y,z; //declares variables of type short int unsigned int x,y,z; //declares variables of type unsigned int char xyz; //declares variable of type char
Initialising Variables by Assigning Values
A variable can be assigned an initial value when created or after creation but these values must be in the correct format. In C, there are three ways to initialise a variable –
Using the assignment operator (=)
int value=10; //creates and initialises variable value of type int to 10
Using parenthesis ()
int value (20) ; //creates and initialises variable value of type int to 20
Using braces {}
int value{30} ; //creates and initialises variable value of type int to 30
An uninitialised variable is a variable that is declared but is not set to a definite known value. An uninitialised variable will have some unknown value known as a “garbage value”. This is due to the variable being assigned a memory location by the compiler and inheriting whatever value happens to be in that memory location. Using the value from an uninitialised variable can result in undefined behaviour and data corruption.
Smaller variables require less memory, and the computer can perform faster mathematical operations. In contrast, large integers and floating-point values require more storage space and thus more time for performing mathematical operations. Using the correct variable types ensures your program runs as efficiently as possible.
Variable Types
Data type | Notes |
char | Store -127 to 127 or 0 to 255. 8 bits. Usually used for holding ASCII characters. |
char16_t | Unsigned integer type. Usually 16 bits. Used for UTF-16 character representation |
char32_t | Unsigned integer type. Usually 32-bit bits. Used for UTF-32 character representation |
wchar_t | Occupies between 16 or 32 bits depending on the compiler being used. Used for Unicode character representation |
signed char | 8 bits. Can store values between -128 to +127. Used for dealing with binary data |
signed short int | Usually at least 16 bits. Can store values between –32,768 to 32,767 |
signed int | Usually at least 16 bits. Can store values between –32,768 to 32,767 |
signed long int | Usually at least 32 bits. Can store values between –2,147,483,648 to 2,147,483,647 |
signed long long int | usually at least 64 bits. Can store values between –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
unsigned char | 8 bits. Can store values between 0 to 255 |
unsigned short int | At least 16 bits. Can store values between 0 to 65,535 |
unsigned int | At least 16 bits. Can store values between 0 to 65,535 |
unsigned long int | At least 32 bits. Can store values between –2,147,483,648 to 2,147,483,647 |
unsigned long long int | At least 64 bits. Can store values between 0 to 4,294,967,295 |
float | Usually 32 bits. Used for storing single precision floating point values. |
double | Usually 64 bits. Used for storing double precision floating point values |
long double | Usually 96 bites. Used for storing long double-precision floating point values |
Variable Scope
A scope is a region of a program, and the scope of variables refers to the area of the program where a variable exists and can be accessed after its declaration.
In C, programming variables can be declared in three places:
- Inside a function or a code block. These are known as local variables and are only valid inside the block they are defined.
- Outside of all functions. These are known as global variables and can be accessed in any part of the program.
- In the function parameters (formal parameter).
When a local variable is defined, it is not initialised by the system and must be initialised by the program. Global variables are initialised automatically by the system.
Using Type Definitions
The typedef declaration provides a way to declare an identifier as an alias or shortcut for an existing variable type. When compiled, the compiler substitutes the identifier with the variable type. Typedef does not create a distinctive variable type but establishes a synonym for an existing variable type –
typedef int aliasint; //create an alias for int name aliasint aliasint v=12; //creates int variable v and set to 12
Sizeof
The sizeof() operator returns the size in bytes of a variable or a type. Since the sizes of a variable or data types can differ between computing environments, knowing the size of a variable in all situations can be useful. The following program lists the size of the C variable types –
#include <stdio.h> int main(void) { printf( "\nA char is %d bytes", sizeof( char )); printf( "\nAn int is %d bytes", sizeof( int )); printf( "\nA short is %d bytes", sizeof( short )); printf( "\nA long is %d bytes", sizeof( long )); printf( "\nA long long is %d bytes\n", sizeof( long long)); printf( "\nAn unsigned char is %d bytes", sizeof( unsigned char )); printf("\nAn unsigned int is %d bytes", sizeof( unsigned int )); printf("\nAn unsigned short is %d bytes", sizeof( unsigned short )); printf("\nAn unsigned long is %d bytes", sizeof( unsigned long )); printf("\nAn unsigned long long is %d bytes\n",sizeof( unsigned long long)); printf( "\nA float is %d bytes", sizeof( float )); printf( "\nA double is %d bytes\n", sizeof( double )); printf( "\nA long double is %d bytes\n", sizeof( long double )); return 0; }
Enumerations
An enumeration is a user-defined data type that consists of integral constants called enumerators. An enum variable takes only one value out of many prescribed values and returns a numeric value corresponding to the selected enumeration. These constants can then be used anywhere that an integer can. Enumerations are defined using the keyword enum followed by the type-name and then the variable-list.
The enumeration list is a comma-separated list of names representing the enumeration values. The variable list is optional because variables may be declared later using the enumeration type name. Although enumerated constants are automatically converted to integers, integers are not automatically converted into enumerated constants.
The following code declares an enumerator called month with the first enum variable value set to one. An enumerator variable is declared called now and set to the value jun. The value of 6 is then output to the screen.
#include <stdio.h> enum month {Jan=1, Feb, Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec }; int main() { // creating now variable of enum month type enum month now; now = Jun; printf("Day %d",now); return 0; }
Extern
The extern keyword enables the programmer to declare a variable without defining it. In programs consisting of several files, each file must be aware of the global variables defined outside that file. The declaration informs the compiler that a variable by that name and type exists and the compiler does not need to allocate memory for it.. The syntax is –
extern int x; //declares a int x value which has been defined elsewhere
- Details
- Category: C category list
- Hits: 174
Constants
Constants or literals refer to fixed values that the program may not alter after they have been defined. Constants can be of any basic data type such as an integer or character.
C has two types of constants:
- Literal Constants
- Symbolic Constants
Literal Constants
A literal constant is a hard code value that is typed directly into the source code such as a number, character, or string that may be assigned to a variable or symbolic constant.
Symbolic Constants
A symbolic constant is an identifier representing a constant value. Whenever a constant value is required the constant name can be used in place of that value throughout the program thus the value of the symbolic constant only needs to be entered when it is first defined. Symbolic constants can be defined using the preprocessor directive #DEFINE or the const keyword.
Defining Constants Using #define - The #define directive enables a simple text substitution that replaces every instance of the name in the code with a specified value with the compiler only seeing the final result. Since these constants don't specify a type, the compiler cannot ensure that the constant has a proper value and their use is discouraged. The prototype of a define directive is -
#define PI 3.14
In the above example, every incidence of the constant directive PI will be replaced by 3.14
Defining Constants with the const Keyword prefix - Variables declared const can’t be modified when the program is executed. A value is initialised at the time of declaration and is then prohibited from being changed.
In the code sample below the value, PI is declared as both a const variable and a preprocessor directive
#define PI 3.14 //set value of constant directive int main() { const float PIVALUE= 22.0 / 7; //set value of constant printf( "\nValue of constand variable PI %f", PIVALUE); printf( "\nValue of constant directive PI %f", PI); return 0; }
Constants are often fully capitalised by programmers to make them distinct from variables. This is not a requirement but the capitalisation of a constant must be consistent in any statement since all variables are case sensitive.
- Details
- Category: C category list
- Hits: 92
Expressions statements and operators
All C programs are made up of statements, which are commands given to the computer executed in sequence. These statements are usually written one per line, although this is not a coding requirement. C statements always end with a semicolon except for preprocessor directives.
Whitespace
Whitespace refers to characters that are used for formatting purposes. In C, this refers primarily to spaces, tabs, and newlines. The C compiler generally ignores whitespace, with a few minor exceptions. Whitespace serves the purpose of making the code more readable to programmers.
Null Statements
A null statement is a semicolon on a line that performs no action.
Compound Statements
A compound statement or block comprises one or more statements enclosed within a bracket.{}
Although every statement in a compound statement must end with a semicolon, the compound statement itself does not end with a semicolon. Variables declared within the statement are local to that compound statement.
Operators
An operator is a symbol that tells the compiler to perform a specific mathematical or logical operation. C operators fall into several categories: assignment operators, mathematical operators, relational operators, and logical operators.
Assignment Operator - is used to assign a value to a variable. The Assignment Operator is denoted by equal to sign. An assignment Operator is a binary operator which operates on two operands. The following table lists the assignment operators supported by the C language -
Operator | Description | Example |
= | Assigns values from right side operand to left side operand | C = A + B will assign the value of A + B to C |
+= | Adds the right operand to the left operand and assigns the result to the left operand. | C += A is equivalent to C = C + A |
-= | Subtracts the right operand from the left operand and assigns the result to the left operand. | C -= A is equivalent to C = C - A |
*= | Multiplies the right operand with the left operand and assigns the result to the left operand. | C *= A is equivalent to C = C * A |
/= | Divides the left operand with the right operand and assigns the result to the left operand. | C /= A is equivalent to C = C / A |
%= | Calculates the modulus of two operands and assigns the result to the left operand. | C %= A is equivalent to C = C % A |
<<= | Left shift AND assignment operator. | C <<= 2 is same as C = C << 2 |
>>= | Right shift AND assignment operator. | C >>= 2 is same as C = C >> 2 |
&= | Bitwise AND assignment operator. | C &= 2 is same as C = C & 2 |
^= | Bitwise exclusive OR and assignment operator. | C ^= 2 is same as C = C ^ 2 |
|= | Bitwise inclusive OR and assignment operator. | C |= 2 is same as C = C | 2 |
The Mathematical Operators - C’s arithmetic operator performs mathematical operations such as addition, subtraction, and multiplication on numerical values
assuming a=2 and b=1
Operator | Description | Example |
+ | Adds two operands | A + B will give 3 |
- | Subtracts the second operand from the first | A - B will give 1 |
* | Multiplies both operands | A * B will give 2 |
/ | Divides the numerator by de-numerator | A / B will give 2 |
% | Modulus Operator and the remainder after an integer division | A % B will give 0 |
++ | increases operator value by one | A++ will give 3 |
-- | decreases operator value by one | A-- will give 1 |
Postfix or Prefix? - In C the increment ++ operator increases the value of a variable by 1 and the use of decrement -- operator decreases the value of a variable by 1. The operator placement has an important effect on the way the operations are evaluated
Placing the operator before the operand ie ++var causes the variable to be increased before it returns a value
Placing the operator after the operand ie var+ causes the value of the variable to be returned before it is incremented by 1
Relational Operators - checks if the values of two operands are equal.
assuming a=2 and b=1
Operator | Description | Example |
---|---|---|
== | returns true (1) if two operands have the same value otherwise returns false (0) | (A == B) is not true. |
!= | returns true (1) if two operands don't have the same value otherwise returns false (0) | (A != B) is true. |
> | returns true (1) if the left operand is greater than the value of the right operand otherwise returns false (0) | (A > B) is true. |
< | returns true (1) if the left operand is less than the value of the right operand otherwise returns false (0) | (A < B) is false. |
>= | returns true (1) if the left operand is greater than or equal to the value of the right operand otherwise returns false (0) | (A >= B) is true. |
<= | returns true (1) if the left operand is less than or equal to the value of the right operand otherwise returns false (0) | (A <= B) is false. |
Logical Operators - applies standard boolean algebra operations to their operands
Assume variable A holds 2 and variable B holds 1, then −
Operator | Description | Example |
---|---|---|
&& | the logical AND operator evaluates two expressions. If both expressions are true, the logical AND expression is true. | A==2 && B==1 result is TRUE |
|| | The logical OR operator evaluates two expressions. If either is true, the expression is true | A==2 || B==1 result is TRUE |
! | A logical NOT statement reverses a normal expression, returning true if the expression is false and false if the expression is true. | !(A==2) result is FALSE |
Bitwise Operators - perform manipulations of data at the bit level. These operators also perform the shifting of bits from right to left. Bitwise operators are not applied to float or double. The difference between logical and bitwise operators is that bitwise operators don’t return a boolean result but manipulate individual bits.
The Bitwise operators supported by the C language are listed in the following table. Assume variable A holds 50 and variable B holds 25, then −
A = 0011 0010
B = 000 11001
Operator | Description | Example |
---|---|---|
& | Binary AND Operator copies a bit to the result if it exists in both operands. | (A & B) will give 16 which is 0001 0000 |
| | Binary OR Operator copies a bit if it exists in either operand. | (A | B) will give 59 which is 0011 1011 |
^ | Binary XOR Operator copies the bit if it is set in one operand but not both. | ">(A ^ B) will give 43 which is 00010 1011 |
~ | is a unary operator and has the effect of 'flipping' the bits. | (~A ) will give -51 which is 1111111111001101 in 2's complement form. |
<< | Binary Left Shift Operator. The left operand value is moved left by the number of bits specified by the right operand. | A << 1 will give 100 which is 0110 0100 |
>> | Binary Right Shift Operator. The left operand value is moved right by the number of bits specified by the right operand. | A >> 2 will give 12 which is 0000 1100 |
Misc Operators
? or ternary operator - Can be used to replace if-else statements
example:y = (x > 10) ? 10 : 20;
Here, y is assigned the value of 10 if x is greater than 10 and 20 if not
. ->(dot and arrow) ---- used to reference individual structures and unions.
&(ampersand) ---- returns the address of a variable. For example, &x; returns the location of the variable x in memory
*(asterisk) ---- Used to Declare and Dereference a pointer.
Operator Precedence in C++
Operator precedence is the order in which operators are evaluated in a compound expression. In C++, when the compiler encounters an expression, it must similarly analyse and determine how it should be evaluated. To assist with this, all operators are assigned a level of precedence. Those with the highest precedence are evaluated first.
Here, operators with the highest precedence appear at the top of the table, and those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
for example
int myNumber = 20 * 50 + 25 – 25 * 25 << 2;
simplifies to 1000+25-625>>2
simplifies to 400>>2=100
Rank | Name | Operator |
---|---|---|
1 | Scope resolution | :: |
2 | Member selection, subscripting, increment, and decrement | . -> |
2 | Member selection, subscripting, increment, and decrement | . ->()++ -- |
3 | sizeof, prefix increment and decrement, complement, and, not, unary minus and plus, address-of and dereference, new, new[], delete, delete[], casting, sizeof() | ++ --^ !- +& *() |
4 | Member selection for a pointer | .* ->* |
5 | Multiply, divide, modulo | * / % |
6 | Add, subtract | + - |
7 | Shift (shift left, shift right) | << = >>= |
8 | Inequality relational | == != |
9 | Equality, inequality | == != |
10 | Bitwise AND | & |
11 | Bitwise exclusive OR | ^ |
12 | Bitwise OR |Rank Name Operator | | |
13 | Logical AND && | && |
14 | Logical OR | || |
15 | Conditional | ?: |
16 | Assignment operators | = *= /= %= += -= <<= >>= &= |= ^= |
17 | comma | , |
- Details
- Category: C category list
- Hits: 98
Controlling Program Flow
Program flow is the order in which individual programming statements are evaluated. In c execution starts at the beginning of the main() function and ends when the end of main() is reached however the C language includes a variety of program control statements that let the programmer control the order of program execution.
The if Statement
The if statement evaluates an expression and executes statement(s) based on the outcome of this evaluation. The statement(s) are only executed if the condition evaluates to true. If the condition evaluates to false, execution is skipped and the program control passes to the statement following the if statement. Control over program execution is through the use of these compound statements which are blocks of code enclosed in brackets
The syntax of the if statement is
if (condition)
{
statement 1;
statement 2;
}
The if-else Statement - causes one of the two possible statement(s) to execute, depending upon the outcome of the predefined condition.
The syntax of the if...else statement is
if (condition)
{
// code block if condition is true
Statement 1;
}
else
{
// code block if condition is not true
Statement 2;
}
If expression evaluates to true, statement1 is executed. If the expression evaluates to false, control passes to the else statement and statement2 is then executed.
Nested if-else - contains one or more if-else statements and is validated against several different conditions, which themselves may be dependent on the evaluation of a previous condition
if( expression1 )
// code block if expression 1 is true
statement1;
else if( expression2 )
// code block if expression 2 is true and expression 1 is false
statement2;
else
// code block if previous conditions are all false
statement3;
If expression1 is evaluated to true, statement1 is executed before the program continues. If the expression1 is not true, expression2 is checked and if it evaluates to true statement2 is executed. If both expression1 and expression2 are false, statement3 is executed. Only one of the three statements is executed.
One-line statement - If there is only one statement to execute after the if condition then the use of curly braces is optional. If there are multiple statements without curly braces then only the statement after the "if" condition gets conditionally executed; the rest of the statement will get executed separately and not as part of the expression. It is therefore considered good practice to use curly braces to prevent confusion and cover the possibility that the programmer may add statements to the block.
Switch Statement
The switch-case conditional statement checks a particular expression against a host of possible constant conditions and performs a different action for each of those different values. Each case statement is ended with an optional break statement that causes execution to exit the code block. In most situations you will want a break ending each section however in some situations you may want to execute multiple case statements. if a break statement does not end the statement sequence associated with a case, then all the statements at and below the matching case will be evaluated
The following is the syntax of a switch-case construct:
switch(expression) { case optionA: DoSomething; break; case optionB: DoSomethingElse; break; default: CatchAllWhenExpressionIsNotHandledAbove; break; }
Looping
Many tasks in a program are accomplished by carrying a repetitive series of instructions, a fixed number of times or until a specific condition is met. A block of such code is called a loop. Each pass through the loop is called an iteration and the blocks of code are called compound statements.
The for Statement
Is an iterative control flow statement which allows code to be executed a specific number of times. The exit condition is checked at the beginning of every loop, and the value of the variable is incremented at the end of a loop. The syntax of a loop is –
for ( init; condition; increment )
{
statement(s);
}
The optional init step is executed first, and only once and allows the programmer to declare and initialize any loop control variables. If no initialisation is specified a semicolon must be used. Following initialisation, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment statement. This process is repeated until the condition becomes false, after which the loop terminates. In the code section below, the for loop is declared and the variable initialised i to 0. The value of value i is then checked and if the exit condition (i<10) is not met the body is executed. The variable i is then incremented at the end of the loop and the process is repeated until the condition statement return false and the loop exits.
#include <stdio.h> int main( void ) { for (int i = 0; i < 10; i++) { printf("%i",i); } return 0; }
Leaving any parameter blank in a for-next declaration means that the condition will start with a null value. You can create an infinite loop by using for(;;)
Advanced for Loops – It is possible to create and run multiple loops within one statement. When the initialization and action sections contain more than one statement, they are separated by commas –
for (int a = 0, b = 0; a < 10; a++, b++)
This loop has two variable initialisations: a and b, each separated by a comma. The loop’s test section tests whether a < 10 and both integer variables are incremented.
Nested Loops – Loops can be nested with one loop sitting in the body of another. The inner loop will be executed in its entirety for every execution of the outer loop.
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
while Loops
A while loop causes a code block to be executed repeatedly as long as a starting condition remains true. The while keyword is followed by an expression in parentheses. If the expression is true, the statements inside the loop block are executed and executed repeatedly until the expression is false. If the initial condition is not met code the block is not executed –
while(condition)
{
statement(s);
}
To note, this statement does not end in a semicolon. The statements inside the loop are surrounded by {} braces indicating the start and end of a localised block of code.
do-while Loops
A do-while loop is a control flow statement that executes a block of code at least once. In contrast to a while loop which starts with a conditional expression before code execution, the do-while loops check the conditions after the block is executed.
do
{
statement(s);
}
while(condition);
Ending Loops Early
The break Statement-The break statement causes a loop to end immediately, instead of waiting for its condition to be false. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
The continue statement-Continue resumes execution from the top of the loop. The code following it within the block is skipped. Thus, the effect of continue in a while , do...while , or for loop is that it forces the next iteration of the loop to take place, skipping any code in between.
#include <stdio.h> int main () { int a = 0; do { a++; if( a == 5) //check if a=15. skip to end of loop continue; if (a==8) break; printf("%i ",a); } while( a < 20 ); return 0;
}
The goto statement
Goto performs a one-way transfer of control to another point in the program. This requires an unconditional jump ignoring any existing program flow such as nesting and does not cause any automatic stack adjusting. The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:). It's advised to use goto statements with caution and preferably not at all since the use of goto statements can lead to an unpredictable flow of code, difficult-to-read programming(spaghetti code) and in some cases unpredictable variable states.
The syntax for the goto statement is
{
Start: // Called a label
UserCode;
goto Start;
}
Exiting the Program
Under normal circumstances, a C program terminates when execution reaches the closing brace of the main() function. Program termination can, however, be initiated by the program by calling the library function exit(). When the exit() function terminates a program and returns control to the operating system it can pass a status code to the operating system to indicate the program’s success or failure. The syntax of the exit() function is
exit(status);
If the status has a value of 0, it indicates that the program terminated normally. A value of 1 indicates that the program terminated with some sort of error.
To use the exit() function, a program must include the header file stdlib.h. This header file also defines two constants for use as arguments to the exit() function:
#define EXIT_SUCCESS
#define EXIT_FAILURE
- Details
- Category: C category list
- Hits: 100