what is c?
c is a general purpose programming language created by dennis ritchie at the bell laboratories in 1972.
it is a very popular language, despite being old.
C is strongly associated with UNX, as it was developed to write the UNX operating system.
Get started with C
Let us create our first C file.
open codeblock and go to file>New> Empty file.
write the following code and save the file with (.c).
In codeblocks ,it should look like this:
then go to Build> Build and Run to run (execute) the program.
the result will look something to this:
Read the Following Code and Output:
L New Lines
New lines
To inset a new line, you can use the\n character.
Note:
two\n characters after each other will create a blank line:
What is \n exactly?
The new line character(\n) is called an escape sequence.
it forces the cursor to change its position to the beginning of the next linne on the screen. this result in a new line.
More valid escape sequences:
Create a horizontal tab \t
insert a back slash character \\
insert a double quote character \”
Comments in C
Comments are used to explain code, and to make it more readable. It can be used to prevent execution when testing alternative code.
comments can be single-lined and multi-lined.
Single-line comments
single line comments are start with two forward slashes(//).
any text between // and the end of the line is ignored by the compiler(will not be executed).
This example uses a single-line comment before a line of code:
this example uses a single-line comment at the end of a line of code:
C Multi-line comments
multi-line comments start with/* and ends with*/.
Any text between /* and*/ will be ignored by the compiler:
C Variables
A variable is nothing but a name given to a strong area that our programs can manipulate. Each variable in C has a specific type, which determine the size and layout of the variable’s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
the name of the variable can be composed of letters; digits and the underscore characters. It must being either with letter or an underscore. Upper and lower case letters are distinct because C is case-sensitive.
Types of variable
- char(typically a single octal(one byte). it is an integer type).
- int(the most natural size of integer for the machine).
- float(a single-precision floating point value).
- double(a double-precision floating point value).
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows −
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-defined object; and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables are undefined.
Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable. A variable definition has its meaning at the time of compilation only, the compiler needs actual variable definition at the time of linking the program.
A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use the keyword extern to declare a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code.
Example
Try the following example, where variables have been declared at the top, but they have been defined and initialized inside the main function −
#include <stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of c : 30
value of f : 23.333334
The same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example −
// function declaration
int func();
int main() {
// function call
int i = func();
}
// function definition
int func() {
return 0;
}
Lvalues and Rvalues in C
There are two kinds of expressions in C −
-
lvalue − Expressions that refer to a memory location are called “lvalue” expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment.
-
rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment.
Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements −
int g = 20; // valid statement
10 = 20; // invalid statement; would generate compile-time error
Data types
Specifying a data type has several reasons, including resemblance, practicality, and attention-getting. The ability to grasp complicated terminology is usually aided by effective organizing. The concept of a data type is explicitly included in almost all programming languages, albeit factors like simplicity, computability, or regularity frequently constrain the range of acceptable data types. The compiler can often select an effective machine representation with an explicit data type declaration, but the conceptual structure provided by data types should not be undervalued.
Data Types in C
Broadly, there are 5 different categories of data types in the C language, they are:
Type |
Example |
Basic |
character, integer, floating-point, double. |
Derived |
Array, structure, union, etc. |
Enumeration |
enums |
Bool type |
true or false |
void |
Empty value |
Primary Data Types in C Programming
The C language has 5 basic (primary or primitive) data types, they are:
Character (char
):
- We use the keyword
char
for the character data type.
- It is used to store single-bit characters and occupies 1 byte of memory.
You can store alphabets from A-Z(and a-z) and 0-9 digits using char
datatype. For example
char b = 'A';
char c = '0';
char d = 0;
// ERROR
-
For char
datatype, it is necessary to enclose the data within single quotes.
-
You can perform addition and subtraction operations on char
datatype values.
-
The ASCII value of a char
datatype value should not exceed 127.
Integer (int
):
-
We use the keyword int
for the integer data type.
-
The int
data type is used to store non-fractional numbers which include positive, negative, and zero values.
-
The range of int
is -2,147,483,648 to 2,147,483,647 and it occupies 2 or 4 bytes of memory, depending on the system you’re using. For example,
int a = 5550;
int b = -90,
int c = 0;
int d = -0.5; //invalid
-
We can perform addition, subtraction, division, multiplication, bitwise, and modulo operations on int
data type.
Floating-point (float
):
-
We use the keyword float
for a floating-point data type.
-
The keyword float
is used to store decimal numbers.
-
It occupies 4 bytes of memory and ranges from 1e-37 to 1e+37.
- For example,
float a = 0.05;
float b = -0.005.
float c = 1; // it will become c = 1.000000 because of type-casting
-
We can perform addition, subtraction, division, and multiplication operations on float
data type.
Double (double
):
-
We use the keyword double
for the double data type.
-
The double datatype is used to store decimal numbers.
-
It occupies 8 bytes of memory and ranges from 1e-37 to 1e+37.
-
Here is how we use it in code,
double a = 10.09;
double b = -67.9;
-
The double
datatype has more precision than float
so double
gives more accurate results as compared to float
.
-
We can perform addition, subtraction, division, and multiplication operations on double
data type.
Void (void
):
-
This means no value.
-
This data type is mostly used when we define functions.
-
The void
datatype is used when a function does not return any result.
-
It occupies 0 bytes of memory.
-
We use the void
keyword for void data type.
Here is how we use the void
type with functions,
void function() {
//your code goes here
}
Size of different Datatypes in C
-
The size of different data types depends on the compiler and processor types.
-
In short, it depends on the Computer on which you are running the C language and the version of the C compiler that you have installed.
1. char is 1 byte
2. int can be 2 bytes/4 bytes
-
There is a very easy way to remember the size of int
datatype.
-
The size of int
datatype is usually equal to the word length of the execution environment of the program.
-
In simpler words, for a 16-bit environment, int
is 16 bits or 2 bytes, and for a 32-bit environment, int
is 32 bits or 4 bytes.
3. float is 4 bytes
-
The float
datatype is 4 bytes or 32 bits in size.
-
It is a single-precision data type that is used to hold decimal values.
-
It is used for storing large values.
-
float
is a faster data type compared to double
, because double
data type works with very large values, hence it is slow.
4. double is 8 bytes
-
The double
datatype is 8 bytes or 64 bits in size.
-
It can store values that are double the size of what a float data type can store, hence it is called double
.
-
In the 64 bits, 1 bit is for sign representation, 11 bits for the exponent, and the rest 52 bits are used for the mantissa.
-
The double
data type can hold approximately 15 to 17 digits, before the decimal and after the decimal.
5. void is 0 bytes
The void
datatype means nothing, hence it doesn’t have a size.
Before moving on to the range of values for these data types, there is one more important concept to learn, which is Datatype modifiers.
C Data type Modifiers:
There are 4 datatype modifiers in C programming that are used along with the basic data types to categorize them further.
For example, if you say, there is a playground, it can be a park, a playground, or a stadium, but if you say, there is a Cricket ground or a Football stadium, that would make it even more precise.
Similarly, there are modifiers in the C language, to make the primary data types more specific.
The following are the modifiers:
-
signed
-
unsigned
-
long
-
short
As the name suggests,
For example, signed int, unsigned int, short int, long int, etc. are all valid data types in the C language.
long long num = 123456789987654321; // we cannot store a value this big value using int data type.
Now let’s see the range for different data types formed as a result of the 5 primary data types along with the modifiers specified above.
C Data type Value Range
In the table below we have the range for different data types in the C language.
Type |
Typical Size in Bits |
Minimal Range |
Format Specifier |
char |
8 |
-127 to 127 |
%c |
unsigned char |
8 |
0 to 255 |
%c |
signed char |
8 |
-127 to 127 |
%c |
int |
16 or 32 |
-32,767 to 32,767 |
%d , %i |
unsigned int |
16 or 32 |
0 to 65,535 |
%u |
signed int |
16 or 32 |
Same as int |
%d , %i |
short int |
16 |
-32,767 to 32,767 |
%hd |
unsigned short int |
16 |
0 to 65,535 |
%hu |
signed short int |
16 |
Same as short int |
%hd |
long int |
32 |
-2,147,483,647 to 2,147,483,647 |
%ld , %li |
long long int |
64 |
-(263 – 1) to 263 – 1 (Added by C99 standard) |
%lld , %lli |
signed long int |
32 |
Same as long int |
%ld , %li |
unsigned long int |
32 |
0 to 4,294,967,295 |
%lu |
unsigned long long int |
64 |
264 – 1 (Added by C99 standard) |
%llu |
float |
32 |
1E-37 to 1E+37 with six digits of precision |
%f |
double |
64 |
1E-37 to 1E+37 with ten digits of precision |
%lf |
long double |
80 |
1E-37 to 1E+37 with ten digits of precision |
%Lf |
As you can see in the table above, with different combinations of the datatype and modifiers the range of value changes.
When we want to print the value for any variable with any datatype, we have to use a format specifier in the printf()
statement.
What happens if the value is out of Range?
Well, if you try to assign a value to any datatype which is more than the allowed range of value, then the C language compiler will give an error. Here is a simple code example to show this,
#include <stdio.h>
int main() {
// allowed value up to 65535
unsigned short int x = 65536;
return 0;
}
Output
warning: large integer implicitly truncated to unsigned type [-Woverflow]
unsigned short int x = 65536; ^
What does signed
and unsigned
means?
This is a little tricky to explain, but let’s try.
-
In simple words, the unsigned
modifier means all positive values, while the signed
modifier means both positive and negative values.
-
When the compiler gets a numeric value, it converts that value into a binary number, which means a combination of 0 and 1. For example, 32767 in binary is 01111111 11111111, 1 in binary is 01 (or 0001), 2 is 0010, and so on.
-
In the case of a signed integer, the highest order bit or the first digit from left (in binary) is used as the sign flag.
-
If the sign flag is 0, the number is positive, and if it is 1, the number is negative.
-
And because one bit is used for showing if the number is positive or negative, hence there is one less bit to represent the number itself, hence the range is less.
-
For signed int, 11111111 11111111 means -32,767, and because the first bit is a sign flag to mark it as a negative number, and the rest represents the number.
-
Whereas in the case of unsigned int, 11111111 11111111 means 65,535.
Derived Data types in C
While there are 5 primary data types, there are some derived data types too in the C language which are used to store complex data.
Derived data types are nothing but primary data types but a little twisted or grouped together like an array, structure, union, and pointers.
Operators
Operators are used to perform operations on variables and values.
In the example below, we use the +
operator to add together two values:
Example
int myNum = 100 + 50;
Although the +
operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:
Example
int sum1 = 100 + 50; int sum2 = sum1 + 250; int sum3 = sum2 + sum2;
C divides the operators into the following groups:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Operator |
Name |
Description |
Example |
|
+ |
Addition |
Adds together two values |
x + y |
|
– |
Subtraction |
Subtracts one value from another |
x – y |
|
* |
Multiplication |
Multiplies two values |
x * y |
|
/ |
Division |
Divides one value by another |
x / y |
|
% |
Modulus |
Returns the division remainder |
x % y |
|
++ |
Increment |
Increases the value of a variable by 1 |
++x |
|
— |
Decrement |
Decreases the value of a variable by 1 |
–x |
|
Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=
) to assign the value 10 to a variable called x:
Example
int x = 10;
The addition assignment operator (+=
) adds a value to a variable:
Example
int x = 10;
x += 5;
A list of all assignment operators:
Operator |
Example |
Same As |
|
= |
x = 5 |
x = 5 |
|
+= |
x += 3 |
x = x + 3 |
|
-= |
x -= 3 |
x = x – 3 |
|
*= |
x *= 3 |
x = x * 3 |
|
/= |
x /= 3 |
x = x / 3 |
|
%= |
x %= 3 |
x = x % 3 |
|
&= |
x &= 3 |
x = x & 3 |
|
|= |
x |= 3 |
x = x | 3 |
|
^= |
x ^= 3 |
x = x ^ 3 |
|
>>= |
x >>= 3 |
x = x >> 3 |
|
<<= |
x <<= 3 |
x = x << 3 |
|
Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.
The return value of a comparison is either 1
or 0
, which means true (1
) or false (0
). These values are known as Boolean values, and you will learn more about them in the Booleans and If..Else chapter.
In the following example, we use the greater than operator (>
) to find out if 5 is greater than 3:
Example
int x = 5;
int y = 3;
printf(“%d”, x > y);
A list of all comparison operators:
Operator |
Name |
Example |
|
== |
Equal to |
x == y |
|
!= |
Not equal |
x != y |
|
> |
Greater than |
x > y |
|
< |
Less than |
x < y |
|
>= |
Greater than or equal to |
x >= y |
|
<= |
Less than or equal to |
x <= y |
|
Logical Operators
You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values:
Operator |
Name |
Description |
Example |
|
&& |
Logical and |
Returns true if both statements are true |
x < 5 && x < 10 |
|
|| |
Logical or |
Returns true if one of the statements is true |
x < 5 || x < 4 |
|
! |
Logical not |
Reverse the result, returns false if the result is true |
!(x < 5 && x < 10) |
|
Sizeof Operator
The memory size (in bytes) of a data type or a variable can be found with the sizeof
operator:
Example
int myInt;
float myFloat;
double myDouble;
char myChar;
printf(“%lu\n”, sizeof(myInt));
printf(“%lu\n”, sizeof(myFloat));
printf(“%lu\n”, sizeof(myDouble));
printf(“%lu\n”, sizeof(myChar));