Programming Language  C Types, Operators and Expressions 主講人:虞台文.

Slides:



Advertisements
Similar presentations
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
Advertisements

1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations Imperative Programming, B. Hirsbrunner,
Expressions An expression is a sequence of operands and operators that reduces to a single value expression operator operand An operator is a language-specific.
C programming an Introduction. Types There are only a few basic data types in C. char a character int an integer, in the range -32,767 to 32,767 long.
Chapter 2: Introduction to C++.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations System-oriented Programming, B. Hirsbrunner,
Introduction To C++ Programming 1.0 Basic C++ Program Structure 2.0 Program Control 3.0 Array And Structures 4.0 Function 5.0 Pointer 6.0 Secure Programming.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Types, Operators and Expressions CSE 2031 Fall /5/2015 3:59 PM.
Chapter 2: Introducing Data Types and Operators.  Know Java’s primitive types  Use literals  Initialize variables  Know the scope rules of variables.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Outline Variables 1.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Primitive Data Types and Operations Identifiers, Variables, and Constants Primitive Data Types Byte, short, int, long, float, double, char, boolean Casting.
2440: 211 Interactive Web Programming Expressions & Operators.
C Tokens Identifiers Keywords Constants Operators Special symbols.
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 6 Fundamental Types Dept of Computer Engineering Khon Kaen University.
Chapter 2: Using Data.
UniMAP Sem1-07/08EKT120: Computer Programming1 Week2.
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
Simple Data Types Built-In and User Defined Chapter 10.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
 All C programs are made up of functions that perform operations on variables.  In this lecture we examine variables  Variables are the basic building.
Fundamental Data Types, Operators and Expressions Kernighan/Ritchie: Kelley/Pohl: Chapter 2 Chapter 2, 3.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
1 Homework –Continue Reading K&R Chapter 2 –We’ll go over HW2 at end of class today –Continue working on HW3 Questions?
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 1.
Programming Fundamentals
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
INTRODUCTION TO ‘C’ PROGRAMMING BY Prof. P. PADMANABHAM M.Tech (AE), M.Tech(CS), Ph.D(CS)-FIETE, FIE Director Academics, Bharat Institute Of Engineering.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
Powerpoint Templates Page 1 Programming in C/C++ PS04CINS02.
UNIMAP Sem2-07/08EKT120: Computer Programming1 Week 2 – Introduction to Programming.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Introduction to ‘c’ language
Chap. 2. Types, Operators, and Expressions
Tokens in C Keywords Identifiers Constants
C Short Overview Lembit Jürimägi.
Fundamental Data Types
Chapter 2: Introduction to C++
Introduction to C Programming
C++ Simple Data Types Simple types Integral Floating
C Program Design Data Types
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Types, Operators and Expressions
Basics of ‘C’.
Introduction to C Programming
Chapter-3 Operators.
Lectures on Numerical Methods
Expressions and Assignment
elementary programming
Fundamental Data Types
Homework Finishing Chapter 2 of K&R. We will go through Chapter 3 very quickly. Not a lot is new. Questions?
Module 2 Variables, Data Types and Arithmetic
DATA TYPES There are four basic data types associated with variables:
Presentation transcript:

Programming Language  C Types, Operators and Expressions 主講人:虞台文

Content Variable Names Data Types and Sizes Constants Declarations Arithmetic Operators Relational and Logical Operators Type Conversions Increment and Decrement Operators Bitwise Operators Assignment Operators and Expressions Conditional Expressions Precedence and Order of Evaluation

Programming Language  C Types, Operators and Expressions Variable Names

Variables In C, a variable must be declared before it can be used. Global variables – declared outside any functions – created when the program starts – destroyed when the program terminates Local variables – declared at the start of any block of code, but most are found at the start of each function. – created when the function is called – destroyed on return from that function.

Variable Names Every variable has a name and a value. – The name identifies the variable, the value stores data. Limitation on names – Every variable name in C must start with a letter, the rest of the name can consist of letters, numbers and underscore characters. C recognizes upper and lower case characters as being different. Finally, you cannot use any of C's keywords like main, while, switch etc as variable names. The rules governing variable names also apply to the function names.

Conventions Avoid using only capital letters in variable names. – These are used for names of constants. Some old implementations of C only use the first 8 characters of a variable name. – Most modern ones don't apply this limit though.

Example: Some Valid Variable Names x result outfile bestyet x1 x2 out_file best_yet power impetus gamma hi_score

Keywords of C autobreakcasecharconstcontinuedefaultdo doubleelseenumexternfloatforgotoif intlongregisterreturnshortsignedsizeofstatic structswitchtypedefunionunsignedvoidvolatilewhile

Programming Language  C Types, Operators and Expressions Data Types and Sizes

Basic Data Types char a single byte, capable of holding one character in the local character set int an integer, typically reflecting the natural size of integers on the host machine float single-precision floating point double double-precision floating point The type of an object determines the set of values it can have and what operations can be performed on it.

Modifiers short long signed unsigned

Data Types in Real World type bytesbitsrange char 18  128  127 unsigned char 18 0  255 short int 216  32,768  32,767 unsigned short int  65,535 int ,147,483,648  +2,147,483,647 unsigned int  4,294,967,295 long int ,147,483,648  +2,147,483,647 unsigned long int  4,294,967,295 float 432 single-precision floating point double 864 double-precision floating point long double 864 extended-precision floating point

Data Types in Real World type bytesbitsrange char 18  128  127 unsigned char 18 0  255 short int 216  32,768  32,767 unsigned short int  65,535 int ,147,483,648  +2,147,483,647 unsigned int  4,294,967,295 long int ,147,483,648  +2,147,483,647 unsigned long int  4,294,967,295 float 432 single-precision floating point double 864 double-precision floating point long double 864 extended-precision floating point typebytesbitsrange char 18  128  127 unsigned char 18 0  255 short int 216  32,768  32,767 unsigned short int  65,535 int ,147,483,648  +2,147,483,647 unsigned int  4,294,967,295 long int ,147,483,648  +2,147,483,647 unsigned long int  4,294,967,295 float 432 single-precision floating point double 864 double-precision floating point long double 864 extended-precision floating point

Example: Sizes of C Data Types #include /* view the sizes of C basic data types */ int main() { printf("sizeof(char) == %d\n", sizeof(char)); printf("sizeof(short) == %d\n", sizeof(short)); printf("sizeof(int) == %d\n", sizeof(int)); printf("sizeof(long) == %d\n", sizeof(long)); printf("sizeof(float) == %d\n", sizeof(float)); printf("sizeof(double) == %d\n", sizeof(double)); printf("sizeof(long double) == %d\n", sizeof(long double)); return 0; } #include /* view the sizes of C basic data types */ int main() { printf("sizeof(char) == %d\n", sizeof(char)); printf("sizeof(short) == %d\n", sizeof(short)); printf("sizeof(int) == %d\n", sizeof(int)); printf("sizeof(long) == %d\n", sizeof(long)); printf("sizeof(float) == %d\n", sizeof(float)); printf("sizeof(double) == %d\n", sizeof(double)); printf("sizeof(long double) == %d\n", sizeof(long double)); return 0; }

Example: Sizes of C Data Types #include /* view the sizes of C basic data types */ int main() { printf("sizeof(char) == %d\n", sizeof(char)); printf("sizeof(short) == %d\n", sizeof(short)); printf("sizeof(int) == %d\n", sizeof(int)); printf("sizeof(long) == %d\n", sizeof(long)); printf("sizeof(float) == %d\n", sizeof(float)); printf("sizeof(double) == %d\n", sizeof(double)); printf("sizeof(long double) == %d\n", sizeof(long double)); return 0; } #include /* view the sizes of C basic data types */ int main() { printf("sizeof(char) == %d\n", sizeof(char)); printf("sizeof(short) == %d\n", sizeof(short)); printf("sizeof(int) == %d\n", sizeof(int)); printf("sizeof(long) == %d\n", sizeof(long)); printf("sizeof(float) == %d\n", sizeof(float)); printf("sizeof(double) == %d\n", sizeof(double)); printf("sizeof(long double) == %d\n", sizeof(long double)); return 0; }

Header Files and

Exercises 1. Write a program to determine the ranges of char, short, int, and long variables, both signed and unsigned, by printing appropriate values from standard headers. 2. Write a program to determine the ranges of float, double, and long double variables by printing appropriate values from standard headers.

Exercises 3. Consider the following fragment of program char c=200; printf("c=%??\n", c); Using different format on ??, see its output. Explain it. 4. Change c ’s data type to unsigned char. Redo the same thing.

Exercises 5. Consider the following fragment of program short s=128; printf("s=%??\n", s); Using different format on ??, see its output. Explain it. 6. Change c ’s data type to unsigned short. Redo the same thing.

Programming Language  C Types, Operators and Expressions Constants

Integer constants Floating point constants Character constants String constants Enumeration constants A constant has a value that cannot be changed.

Integer Constants Can be expressed in the following ways: 1234 (decimal) 0xff (Hexidecimal) 0100 (Octal) '\xf' (Hex character)

Example: Integer Constants int i=255;/* i assigned the decimal value of 255 */ i -= 0xff;/* subtract 255 from i */ i += 010;/* Add Octal 10 (decimal 8) */ /* Print 15 - there are easier ways... */ printf ("%i \n", '\xf'); int i=255;/* i assigned the decimal value of 255 */ i -= 0xff;/* subtract 255 from i */ i += 010;/* Add Octal 10 (decimal 8) */ /* Print 15 - there are easier ways... */ printf ("%i \n", '\xf');

Integer Constants Integer constants are assumed to have a datatype of int ; if not fit, the compiler will assume the constant is a long. int long Integer constants with modifiers 1234L /* long int constant (4 bytes) */ 1234U /* unsigned int */ 1234UL /* unsigned long int */

Floating Point Constants Floating point constants contain a decimal point or exponent. By default they are double (double) 1e-2(double) 124.4f(float) 1e-2f(float)

Character Constants Character constants are actually integers, written as one character within single quotes, such as 'x'(an visible character) '\000' (Octal) '\xhh' (Hexadecimal)

Escape Sequences \a alert (bell) character \\ backslash \b backspace \? question mark \f formfeed \' single quote \n newline \" double quote \r carriage return \000 octal number \t horizontal tab \xhh hexadecimal number \v vertical tab

Example: Character Constants

String Constants C does not have a "string" data type. To create a string you have to use a char array or a char pointer. They are actually a sequence of char items terminated with a \0. char str[] = "String Constant"; or char *str = "String Constant";

Example: String Constants

Enumeration Constants enum is closely related to the #define preprocessor. It allows you to define a list of aliases which represent integer numbers. #define SUN 0 #define MON 1 #define TUE 2 #define WED 3 #define THU 4 #define FRI 5 #define SAT 6 #define SUN 0 #define MON 1 #define TUE 2 #define WED 3 #define THU 4 #define FRI 5 #define SAT 6 enum week { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; enum week { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

Example: Weekday

Example: More Enumeration Constants enum boolean { NO, YES }; enum escapes { BELL = '\a', BACKSPACE = '\b', TAB = '\t', NEWLINE = '\n', VTAB = '\v', RETURN = '\r' }; enum months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }; /* FEB = 2, MAR = 3, etc. */ enum boolean { NO, YES }; enum escapes { BELL = '\a', BACKSPACE = '\b', TAB = '\t', NEWLINE = '\n', VTAB = '\v', RETURN = '\r' }; enum months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }; /* FEB = 2, MAR = 3, etc. */

Programming Language  C Types, Operators and Expressions Declarations

Variable Declarations single declarations multiple declarations int lower; int upper; int step; char c; char line[1000]; int lower; int upper; int step; char c; char line[1000]; int lower, upper, step; char c, line[1000]; int lower, upper, step; char c, line[1000];

Declarations and Initializations single declarations multiple declarations int lower; int upper; int step; char c; char line[1000]; int lower; int upper; int step; char c; char line[1000]; int lower, upper, step; char c, line[1000]; int lower, upper, step; char c, line[1000]; int lower=0; int upper=300; int step=20; char c='\0'; char line[1000]; int lower=0; int upper=300; int step=20; char c='\0'; char line[1000]; int lower=0, upper=300, step=200; char c='\0', line[1000]; int lower=0, upper=300, step=200; char c='\0', line[1000];

const  Defined Variables as constants const double e = ; const char msg[] = "warning: "; int strlen(const char[]); const double e = ; const char msg[] = "warning: "; int strlen(const char[]); Variables defined with const qualifier whose values can not be changed. They must have initializers.

Variable Scope & Life Span Variable Scope  – The area of the program where that variable is valid, i.e., – the parts of the program that have access to that variable. – determined by the location of the declaration. Life Span  – the length of time that the variable remains in memory. – determined by the location of the declaration.

Where do you Declare Variables? Outside any function definition –.e.g., Prior to the start of the main() function – Global/external variables Within a function, after the opening { – Local to the function Within a block of code, after the { – Local to the area surrounded by the {} braces

Example: Scope #include int m, n=2; double val1=0.1, val2=0.2; void fun(double); main() { printf("0:val1=%lf,val2=%lf,m=%d,n=%d\n", val1, val2, m, n); fun(val2); printf("3:val1=%lf,val2=%lf,m=%d,n=%d\n", val1, val2, m, n); } void fun(double val1) { int n=1000; val1 = 1.234; val2 = 5.678; for(m=0; m<10; m++){ int n; n = m * 2; printf("1:val1=%lf,val2=%lf,m=%d,n=%d\n", val1, val2, m, n); } printf("2:val1=%lf,val2=%lf,m=%d,n=%d\n", val1, val2, m, n); } #include <stdio.h> int m, n=2; double val1=0.1, val2=0.2; void fun(double); main() { printf("0:val1=%lf,val2=%lf,m=%d,n=%d\n", val1, val2, m, n); fun(val2); printf("3:val1=%lf,val2=%lf,m=%d,n=%d\n", val1, val2, m, n); } void fun(double val1) { int n=1000; val1 = 1.234; val2 = 5.678; for(m=0; m<10; m++){ int n; n = m * 2; printf("1:val1=%lf,val2=%lf,m=%d,n=%d\n", val1, val2, m, n); } printf("2:val1=%lf,val2=%lf,m=%d,n=%d\n", val1, val2, m, n); }

Example: Scope #include int m, n=2; double val1=0.1, val2=0.2; void fun(double val1); main() { printf("0:val1=%lf,val2=%lf,m=%d,n=%d\n", val1, val2, m, n); fun(val2); printf("3:val1=%lf,val2=%lf,m=%d,n=%d\n", val1, val2, m, n); } void fun(double val1) { int n=1000; val1 = 1.234; val2 = 5.678; for(m=0; m<10; m++){ int n; n = m * 2; printf("1:val1=%lf,val2=%lf,m=%d,n=%d\n", val1, val2, m, n); } printf("2:val1=%lf,val2=%lf,m=%d,n=%d\n", val1, val2, m, n); } #include int m, n=2; double val1=0.1, val2=0.2; void fun(double val1); main() { printf("0:val1=%lf,val2=%lf,m=%d,n=%d\n", val1, val2, m, n); fun(val2); printf("3:val1=%lf,val2=%lf,m=%d,n=%d\n", val1, val2, m, n); } void fun(double val1) { int n=1000; val1 = 1.234; val2 = 5.678; for(m=0; m<10; m++){ int n; n = m * 2; printf("1:val1=%lf,val2=%lf,m=%d,n=%d\n", val1, val2, m, n); } printf("2:val1=%lf,val2=%lf,m=%d,n=%d\n", val1, val2, m, n); }

static Variables/Functions /* Example of the static keyword */ char name[100]; /* Variable accessible from all files */ static int i; /* Variable accessible only from this file */ static int max_so_far(int); /* Function accessible only from this file */ int max_so_far(int curr) { static int biggest=0; /* Variable whose value is retained between each function call */ if( curr > biggest ) biggest = curr; return biggest; } /* Example of the static keyword */ char name[100]; /* Variable accessible from all files */ static int i; /* Variable accessible only from this file */ static int max_so_far(int); /* Function accessible only from this file */ int max_so_far(int curr) { static int biggest=0; /* Variable whose value is retained between each function call */ if( curr > biggest ) biggest = curr; return biggest; }

Example static Variables/Functions

Programming Language  C Types, Operators and Expressions Arithmetic Operators

OperationOperatorExample Value of Sum before Value of sum after Multiply *sum = sum * 2; 48 Divide /sum = sum / 2; 42 Addition +sum = sum + 2; 46 Subtraction -sum = sum -2; 42 Increment ++++sum; 45 Decrement ----sum; 43 Modulus %sum = sum % 3; 41

Precedence The binary + and - operators have the same precedence, which is lower than the precedence of *, / and %, which is in turn lower than unary + and -. Arithmetic operators associate left to right.

Example: Precedence -x+y*-z/w*2-x+y/5 (((-x)+(((y*(-z))/w)*2)-x)+(y/5)) x=2; y=10; z=4; w=2;

Example: Precedence

Example: Modulus

only for integer

Programming Language  C Types, Operators and Expressions Relational and Logical Operators

Relation Operators OperatorMeaning == equal to != not equal < less than <= less than or equal to > greater than >= greater than or equal to

Example: Relation Operator

Logical Operators OperatorMeaning && and || or ! not Operand 1Operand 2 op1 || op2op1 && op2! op non-zero

Example: Logical Operator

Exercises 7. Write a function char ucase(char c) that can converts a lowercase letter to uppercase letter, and a program making use it to convert all lowercase letters in the file to uppercase.

Programming Language  C Types, Operators and Expressions Type Conversions

Implicit type conversion – also known as coercion – automatically done by the compiler when type mismatch on operands – narrower type  wider type Explicit type conversion – Done by programmer – Type casting

Implicit Type Conversion General rules for binary operators ( +-*/% etc) – If either operand is long double the other is converted to long double. – Otherwise, if either operand is double the other is converted to double – Otherwise, if either operand is float the other is converted to float – Otherwise, convert char and short to int – Then, if an operand is long convert the other to long.

Example: Coercion

Example: atoi /* atoi: convert s to integer */ int atoi(char s[]) { int i, n; n = 0; for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i) n = 10 * n + (s[i] - '0'); return n; } /* atoi: convert s to integer */ int atoi(char s[]) { int i, n; n = 0; for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i) n = 10 * n + (s[i] - '0'); return n; } Converted to integer before subtraction.

Type Casting (type name) expression

Type Casting (type name) expression

Type Casting (type name) expression

Type Casting (type name) expression

Type Casting (type name) expression

Type Casting (type name) expression

(type name) expression The cast operator has the same high precedence as other unary operators.

Programming Language  C Types, Operators and Expressions Increment and Decrement Operators

Increment and Decrement Operators ++ (Increment Operator) – Prefix: ++n – Postfix: n++ -- (Decrement Operator) – Prefix: --n – Postfix: n-- Prefix: value changed before being used Postfix: value used before being changed

Example: Increment and Decrement Operators

Example: Squeeze /* squeeze: delete all c from s */ void squeeze(char s[], int c) { int i, j; for (i = j = 0; s[i] != '\0'; i++) if (s[i] != c) s[j++] = s[i]; s[j] = '\0'; } /* squeeze: delete all c from s */ void squeeze(char s[], int c) { int i, j; for (i = j = 0; s[i] != '\0'; i++) if (s[i] != c) s[j++] = s[i]; s[j] = '\0'; }

Example: Squeeze

Exercises 8. Write an alternative version of squeeze(s1,s2) that deletes each character in s1 that matches any character in the string s2. 9. Write the function any(s1,s2), which returns the first location in a string s1 where any character from the string s2 occurs, or -1 if s1 contains no characters from s2. (The standard library function strpbrk does the same job but returns a pointer to the location.)

Programming Language  C Types, Operators and Expressions Bitwise Operators

OperationOperatorComment Value of Sum before Value of sum after AND &sum = sum & 2;40 OR |sum = sum | 2;46 Exclusive OR ^sum = sum ^ 2;46 1's Complement ~sum = ~sum;4-5 Left Shift <<sum = sum << 2;416 Right Shift >>sum = sum >> 2;41 1= = = = = = =

Example: Bitwise Operators 1= = = = = = =

Example: getbits unsigned getbits(unsigned x, int p, int n) data position #bits unsigned x; x = getbits(0xabababab, 19, 6); unsigned x; x = getbits(0xabababab, 19, 6); X = ?

Example: getbits unsigned getbits(unsigned x, int p, int n) data position #bits 0xabababab= unsigned x; x = getbits(0xabababab, 19, 6); unsigned x; x = getbits(0xabababab, 19, 6);

Example: getbits unsigned getbits(unsigned x, int p, int n) data position #bits 0xabababab= unsigned x; x = getbits(0xabababab, 19, 6); unsigned x; x = getbits(0xabababab, 19, 6); 0xabababab= X = b = 46 10

0xabababab= Example: getbits unsigned getbits(unsigned x, int p, int n) data position #bits unsigned x; x = getbits(0xabababab, 19, 6); unsigned x; x = getbits(0xabababab, 19, 6); >> & X = b = 46 10

0xabababab= Example: getbits unsigned getbits(unsigned x, int p, int n) data position #bits unsigned x; x = getbits(0xabababab, 19, 6); unsigned x; x = getbits(0xabababab, 19, 6); >> & X = b = p–n+1 ~( )  ~(~0 << n) ~( )  ~(~0 << n)

Example: getbits /* getbits: get n bits from position p */ unsigned getbits(unsigned x, int p, int n) { return (x >> (p+1-n)) & ~(~0 << n); } /* getbits: get n bits from position p */ unsigned getbits(unsigned x, int p, int n) { return (x >> (p+1-n)) & ~(~0 << n); }

Exercises 10. Write a function setbits(x, p, n, y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged. 11. Write a function invert(x, p, n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others unchanged. 12. Write a function rightrot(x, n) that returns the value of the integer x rotated to the right by n positions.

Programming Language  C Types, Operators and Expressions Assignment Operators and Expressions

Assignment Operators i = i + 2;i += 2;  exp 1 op= exp 2 exp 1 = exp 1 op (exp 2 )  x = x * (y + 1); x *= y + 1; 

Assignment Operators OperatorOperation Performed = Simple assignment *= Multiplication assignment /= Division assignment %= Remainder assignment += Addition assignment –= Subtraction assignment <<= Left-shift assignment >>= Right-shift assignment &= Bitwise-AND assignment ^= Bitwise-exclusive-OR assignment |= Bitwise-inclusive-OR assignment

Example: bitcount /* bitcount: count 1 bits in x */ int bitcount(unsigned x) { int b; for (b = 0; x != 0; x >>= 1) if (x & 01) b++; return b; } /* bitcount: count 1 bits in x */ int bitcount(unsigned x) { int b; for (b = 0; x != 0; x >>= 1) if (x & 01) b++; return b; } X= & x = x >> 1

Programming Language  C Types, Operators and Expressions Conditional Expressions

int a, b, z;... if (a > b) z = a; else z = b; int a, b, z;... if (a > b) z = a; else z = b; int a, b, z;... z = a > b ? a : b int a, b, z;... z = a > b ? a : b expr 1 ? expr 2 : expr 3

Example: min/max main() { char str[MAXLINE]; int val1, val2; printf("Enter First integer:"); /* get 1st int string */ getlinestr(str, MAXLINE); val1 = atoi(str); /* convert string to value */ printf("Enter second integer:"); /* get 2nd int string */ getlinestr(str, MAXLINE); val2 = atoi(str); /* convert string to value */ if(val1 <= val2) printf("The min/max are %d/%d\n", val1, val2); else printf("The min/max are %d/%d\n", val2, val1); } main() { char str[MAXLINE]; int val1, val2; printf("Enter First integer:"); /* get 1st int string */ getlinestr(str, MAXLINE); val1 = atoi(str); /* convert string to value */ printf("Enter second integer:"); /* get 2nd int string */ getlinestr(str, MAXLINE); val2 = atoi(str); /* convert string to value */ if(val1 <= val2) printf("The min/max are %d/%d\n", val1, val2); else printf("The min/max are %d/%d\n", val2, val1); }

Example: min/max main() { char str[MAXLINE]; int val1, val2; printf("Enter First integer:"); /* get 1st int string */ getlinestr(str, MAXLINE); val1 = atoi(str); /* convert string to value */ printf("Enter second integer:"); /* get 2nd int string */ getlinestr(str, MAXLINE); val2 = atoi(str); /* convert string to value */ printf("The min/max are %d/%d\n", val1>=val2 ? val2 : val1, /* min(val1, val2) */ val1<val2 ? val2 : val1); /* max(val1, val2) */ } main() { char str[MAXLINE]; int val1, val2; printf("Enter First integer:"); /* get 1st int string */ getlinestr(str, MAXLINE); val1 = atoi(str); /* convert string to value */ printf("Enter second integer:"); /* get 2nd int string */ getlinestr(str, MAXLINE); val2 = atoi(str); /* convert string to value */ printf("The min/max are %d/%d\n", val1>=val2 ? val2 : val1, /* min(val1, val2) */ val1<val2 ? val2 : val1); /* max(val1, val2) */ }

Example: Male/Female int sex; /* 0:female, 1: male */ sex = 1; printf("%s is a good student.\n", sex ? "He", "She"); int sex; /* 0:female, 1: male */ sex = 1; printf("%s is a good student.\n", sex ? "He", "She");

Programming Language  C Types, Operators and Expressions Precedence and Order of Evaluation

Precedence and Order of Evaluation OperatorsAssociativity () [] ->. left to right ! ~ * (type) sizeof right to left * / % left to right + - left to right > left to right >= left to right == != left to right & ^ | && left to right || left to right ?: right to left = += -= *= /= %= &= ^= |= >= right to left, left to right

Example main() { int score, bonus; score = 50; bonus = 10; printf("The final score is %d\n", score + bonus > 0 ? bonus : 0); } main() { int score, bonus; score = 50; bonus = 10; printf("The final score is %d\n", score + bonus > 0 ? bonus : 0); }

Example main() { int score, bonus; score = 50; bonus = 10; printf("The final score is %d\n", score + (bonus > 0 ? bonus : 0)); } main() { int score, bonus; score = 50; bonus = 10; printf("The final score is %d\n", score + (bonus > 0 ? bonus : 0)); }