Data Types and Operators Prepared by Dr Haitham
Data Types and Operators Prepared by: Dr. Haitham Tayyar 1
The C Language Currently, the most commonly-used language for embedded systems “High-level assembly” Very portable: compilers exist for virtually every processor Easy-to-understand compilation Produces efficient code Fairly concise 2
C History Developed between 1969 and 1973 along with Unix Due mostly to Dennis Ritchie Designed for systems programming Ø Operating systems Ø Utility programs Ø Compilers 3
Hello World in C #include <stdio. h> int main() { printf(“Hello, world!n”); } 4
Hello World in C #include <stdio. h> int main() { printf(“Hello, world!n”); } Program mostly a collection of functions “main” function special: the entry point “int” qualifier indicates function returns an integer I/O performed by a library function: not included in the language 5
Pieces of C Types and Variables (LO 2) Ø Definitions of data in memory Expressions (LO 2) Ø Arithmetic, logical, and assignment operators in an infix notation Statements (LO 3) Ø Sequences of conditional, iteration, and branching instructions Functions (LO 4) Ø Groups of statements and variables invoked recursively 6
Data types Name Description Size* Range* char Character or small integer 1 byte signed: -128 to 127 unsigned: 0 to 255 short int (short) Short integer 2 bytes signed: -32768 to 32767 unsigned: 0 to 65535 int Integer 4 bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 long int (long) Long integer 4 bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 float Floating point number 4 bytes 3. 4 e +/- 38 (7 digits) double Double precision floating point number 8 bytes 1. 7 e +/- 308 (15 digits) long double Long double precision floating point number 8 bytes 1. 7 e +/- 308 (15 digits) 7
Variable types Local variables are declared within the body of a function, and can only be used within that function. Static variable Another class of local variable is the static type. It is specified by the keyword static in the variable declaration. The most striking difference from a non-static local variable is, a static variable is not destroyed on exit from the function. Global variable A global variable declaration looks normal, but is located outside any of the program's functions. So it is accessible to all functions. 8
Variables • A variable is a name that represents one or more memory locations used to hold program data • A variable may be thought of as a container that can hold data used in a program 5 int my. Variable; my. Variable = 5; my. Var iable 9
An example int global = 10; int func (int x) { static int stat_var; int temp; int name[50]; …… } //global variable //static local variable //(normal) local variable 10
Variables • Variables are names for storage locations in memory 15 int warp_factor; Data Memory (RAM) 0 41 char first_letter; ‘A’ float length; 5. 74532370373175 × 10 -14 11
Variables • Variable declarations consist of a unique identifier (name)… 15 int warp_factor; Data Memory (RAM) 0 41 char first_letter; ‘A’ float length; 5. 74532370373175 × 10 -14 12
Variables …and a data type Determines size and how values are interpreted int warp_factor; 15 Data Memory (RAM) 0 41 char first_letter; ‘A’ float length; 5. 74532370373175 × 10 -44 13
Identifiers • Names given to program variables • Valid characters in identifiers: Identifier First Character ‘_’ (underscore) ‘A’ to ‘Z’ ‘a’ to ‘z’ Remaining Characters ‘_’ (underscore) ‘A’ to ‘Z’ ‘a’ to ‘z’ ‘ 0’ to ‘ 9’ • Case sensitive! • Only first 31 characters significant 14
Variables How to Declare a Variable? Syntax type identifier 1, identifier 2, …, identifiern; • A variable must be declared before it can be used • The compiler needs to know how much space to allocate and how the values should be handled Examples int x, y, z; float warp. Factor; char text_buffer; unsigned index; 15
Variables How to Declare a Variable? Variables may be declared in a few ways: Syntax One declaration on a line type identifier; One declaration on a line with an initial value type identifier = Initial. Value; Multiple declarations of the same type on a line type identifier 1, identifier 2, identifier 3; Multiple declarations of the same type on a line with initial values type identifier 1 = Value 1, identifier 2 = Value 2; 16
Variables How to Declare a Variable Examples int x; int y = 12; int a, b, c; long int my. Var = 0 x 12345678; long z; char first = 'a', second, third = 'c'; float big_number = 6. 02 e+23; 17
A Simple C Program Preprocessor Directives Header File #include <stdio. h> int main(void) { float radius, area, PI; Variable Declarations //Calculate area of circle radius = 12. 0; PI = 3. 1416; area = PI * radius; printf("Area = %f", area); Function Comment } 18
A Simple C Program Variables and Data Types #include <stdio. h> Data Types int main(void) { Variable float radius, area, PI; Declarations //Calculate area of circle PI = 3. 1416; radius = 12. 0; area = PI * radius; Variables in use printf("Area = %f", area); } 19
printf() The printf() function can be instructed to print integers, floats and string properly. The general syntax is printf( “format”, variables); An example int stud_id = 5200; char name[20] = “Mike”; // array discussed in LO 4 printf(“%s ‘s ID is %d n”, name, stud_id); 20
printf() Format Identifiers %d %x %c %f %lf %s %p %e decimal integers hex integer character float number double number string pointer decimal exponent How to specify display space for a variable? printf(“The student id is %5 d n”, stud_id); The value of stud_id will occupy 5 characters space in the print-out. 21
Why “n” It introduces a new line on the terminal screen. escape sequence a alert (bell) character \ backslash b backspace ? question mark f formfeed ’ single quote n newline ” double quote r carriage return 00 octal number t horizontal tab xhh hexadecimal number v vertical tab 22
printf() 23
scanf() Description: The C library function int scanf(const char *format, . . . ) reads formatted input from keyboard. The function returns how many values where read. If scanf returns a 0 it means nothing was read. Declaration: Following is the declaration for scanf() function. int scanf(const char *format, . . . ) Example: int a, result; result = scanf("%d", &a); 24
scanf() Example: The following example shows the usage of scanf() function to read strings. Note: in scanf, we do not use & with array names #include <stdio. h> int main() { char str 1[20], str 2[30]; printf("Enter name: "); scanf("%s", str 1); printf("Enter your website name: "); scanf("%s", str 2); printf("Entered Name: %sn", str 1); printf("Entered Website: %s", str 2); } Enter name: admin Enter your website name: www. tutorialspoint. com Entered Name: admin Entered Website: www. tutorialspoint. com 25
scanf() Is a function in C which allows the programmer to accept input from a keyboard. The following program illustrates the use of this function. #include <stdio. h> main() { int pin; printf("Please type in your PINn"); scanf("%d", &pin); printf("Your access code is %dn", pin); } What happens in this program? An integer called pin is defined. A prompt to enter in a number is then printed with the first printf statement. The scanf routine, which accepts the response, has a control string and an address list. In the control string, the format specifier %d shows what data type is expected. The &pin argument specifies the memory location of the variable the input will be placed in. After the scanf routine completes, the variable pin will be initialized with the input integer. This is confirmed with the second printf statement. The & character has a very special meaning in C. It is the address operator. 26
Arithmetic Operations Operator * / % + + (unary) - (unary) Operation Example Result Multiplication Division Modulo x*y x/y x%y Addition Subtraction x+y x-y Positive Negative +x -x Product of x and y Quotient of x and y Remainder of x divided by y Sum of x and y Difference of x and y Value of x Negative value of x NOTE - An int divided by an int returns an int: 10/3 = 3 Use modulo to get the remainder: 10%3 = 1 27
Arithmetic Assignment Operators 28
Relational Operations Operator Operation Example Result (FALSE = 0, TRUE ≠ 0) < Less than x<y True if x less than y, else false <= Less than or equal to x <= y True if x less than or equal to y, else false > Greater than x>y >= Greater than or equal to x >= y True if x greater than or equal to y, else false == Equal to x == y True if x equal to y, else false != Not equal to x != y True if x not equal to y, else false True if x greater than y, else false 29
Increment and Decrement Operators awkward easy easiest x = x+1; x += 1 x++ x = x-1; x -= 1 x-- 30
Example Arithmetic operators int i = 10; int j = 15; int add = i + j; int diff = j – i; int product = i * j; int quotient = j / i; int residual = j % i; i++; i--; //25 // 150 // 1 // 5 //Increase by 1 //Decrease by 1 31
Example Comparing them int i = 10; int j = 15; float k = 15. 0; j/i=? j%i=? k/i=? k%i=? The Answer j / i = 1; j % i = 5; k / i = 1. 5; k % i It is illegal. Note: For %, the operands can only be integers. 32
Logical Operations What is “true” and “false” in C In C, there is no specific data type to represent “true” and “false”. C uses value “ 0” to represent “false”, and uses nonzero value to stand for “true”. Logical Operators A && B => A || B => A == B => A != B => A and B A or B Is A equal to B? Is A not equal to B? 33
Logical Operations A >B A >= B A <= B => => Is A greater than B? Is A greater than or equal to B? Is A less than or equal to B? Don’t be confused && and || have different meanings from & and | are bitwise operators. 34
No operator for exponent in C • 35
OPERATOR PRECEDENCE Precedence and Associativity of C Operators Symbol Type of Operation Associativity [ ] ( ). –> postfix ++ and postfix –– Expression Left to right prefix ++ and prefix –– sizeof Unary Right to left & * + – ~ ! typecasts Unary Right to left * / % Multiplicative Left to right + – Additive Left to right << >> Bitwise shift Left to right < > <= >= Relational Left to right == != Equality Left to right & Bitwise-AND Left to right ^ Bitwise-exclusive-OR Left to right | Bitwise-inclusive-OR Left to right && Logical-AND Left to right || Logical-OR Left to right ? : = *= /= %= += –= <<= >>= &= ^= |= , Conditional-expression Right to left Simple and compound assignment Right to left Sequential evaluation Left to right 36
Some practices Compute the value of the following logical expressions? int i = 10; int j = 15; int k = 15; int m = 0; if( i < j && j < k) => if( i != j || k < j) => if( j<= k || i > k) => if( j == k && m) => if(i) => if(m || j && i ) => 37
Answers int i = 10; int j = 15; int k = 15; int m = 0; if( i < j && j < k) => false if( i != j || k < j) => true if( j<= k || i > k) => true if( j == k && m) => false if(i) => true if(m || j && i ) => true 38
- Slides: 38