Presentation is loading. Please wait.

Presentation is loading. Please wait.

C Basics Topic 2.

Similar presentations


Presentation on theme: "C Basics Topic 2."— Presentation transcript:

1 C Basics Topic 2

2 Plan of the Day C & high level languages C editors
text editor and command line IDE: CLion First programming concepts basic syntax, output with printf identifiers, keywords, comments, types variables, assignment operators, constants

3 Fun Facts about C

4 C Features & Uses Few keywords
Compound data types (structures, unions) Pointers External library for I/O, other facilities Used for Systems programming: OS like Linux, embedded processors, microcontrollers... Recommendations Use tools (IDE, lint, debuggers, etc.) to make programs more reliable. Use libraries of existing code (both to save time and increase reliability). Adopt a sensible set of coding conventions. Avoid programming “tricks” and complicated code. Efficient: intended for traditional use of assembly and it was crucial to run quickly Portable: real strength resulting from early association with Unix and ANSI standards Power: lots of data types and operators Flexibility: used for systems programming, embedded systems to commercial data processing Standard Library: hundreds of functions for I/O, String handling, storage and other ops Integration with UNIX: Error prone: Difficult to Understand: terse, short programs Difficult to Modify: Lacks classes and packages to help organize.

5 C: A low-level language
C does not have: exceptions for error-handling range-checking garbage collection OO programming String type So... be careful: Recommendations Always use a debugger like gdb (more about this later) Use libraries of existing code (both to save time and increase reliability). Adopt a sensible set of coding conventions. Avoid programming “tricks” and complicated code. low level  faster (usually)

6 C Standards Three C Standards: ANSI C: from late 80s (aka C89)
C99: standard from 1999 New built-in types (e.g., _Bool) stdbool.h provides bool Added variable-length arrays, single line comments, declarations and code mixing C11: current standard, released in 2011 Improved Unicode support (char16_t, char32_t types for storing UTF-16, UTF-32 encoded data) First standard for language published by ANSI. C89 C90 is essentially the same language – some formatting changes C11: also deprecated gets

7 High Level Languages Assembly language: better than sequences of bits lots of commands to accomplish things High Level Computer Languages: accomplish a lot with fewer commands compared to machine or assembly language easier to understand instructions translated/compiled into machine instructions int sum = 0; int count = 0; while( list[count] != -1 ) { sum += list[count]; count = count + 1; } Machine language: fundamental language of any computer, sequences of 0s and 1s Assembly language: a bit higher level language – uses mnemonics and symbols for the binary machine instructions assembler: maps assembly lang instrs into machine lang machine dependent: each comp architecture has its own assembly lang low level instrs – tedious, time consuming

8 Structure of a C Program
#include<something.h> int main(void) { <statement>; ... } Stored in .c file Every executable C program contains main function containing statements to be executed function: a named group of statements statement: a command to be executed Braces define a block Always enclose a function's instructions with braces block – code that is treated as a unit, surrounded by curly braces

9 Structure of a C Program
Preprocessor directives like #include Ex: #include<stdio.h> contains information about C’s standard I/O library Functions – named set of statements that carry out a task block of statements in a function is executed in sequence, one after the other, i.e. single thread of execution. Each statement consists of legal words, symbols and punctuation (tokens) from the C alphabet. A statement ends with a “;” Preprocessor libraries in binary format – companion files to a library, header files, give plain-text declarations for the library utilities Note: Preprocessor substitutes text of included files where the #include appears If you have a header file in working directory of project use quotes: #include "myHeader.h" case sensitive, free form layout – use of whitespace for readability – not required by compiler return not required in main – traditionally included Must have a main function – where execution begins int return type – the value produced by the function is an integer void: main has no arguments (use of void is optional) #define – used to define macro definitions Defining constants to be used in program, e.g., #define PI 3.14 File: hello.c #include <stdio.h> int main(void) { printf(“Hello World\n”); /*function call */ return 0; } Output: Hello World main printf string

10 Build Process with gcc

11 Source Code to Executable
Two types of source code files: regular code (files end in .c) header files (files end in .h) Compiler turns source code into object code files end in .o Linker turns object code files into executable a.out by default Preprocessor is usually integrated with compiler Object code is usually machine language (i.e., understood by a specific CPU like x86, PowerPC). May be an executable (that is, runnable) or it may need linking with other object code files like libraries to produce a complete executable program.

12 Source Code to Executable
gcc program is compiler and linker % gcc hello.c –o hello What happens? gcc does this: compiles hello.c to hello.o links hello.o with system libraries produces binary executable hello -Wall enables compiler warnings gcc –Wall –o hello hello.c -g embeds debugging info gcc –g hello.c compiling: source code to object code linking: object code files to binary executable Executable on Windows ends in .exe -Wall flag: asks compiler to list all warnings about parts of program that are "correct" by questionable – known as static analysis (modern C compilers good at this)

13 Compilation with gcc GNU C Compiler gcc: gcc compilation process
included on unix Available via MinGW or Cygwin on Windows Specify output file with –o option (default is a.out) gcc compilation process % gcc –o hello hello.c % ./hello Hello World % gcc hello.c % ./a.out Hello World Richard Stallman, founder of the GNU project source code (.c, .h) Preprocessing Include header, expand macro (.i) Step 1: Pre-processing: includes the headers (#include .h files) and expands the macros (#define) >> cpp hello.c > hello.i (hello.i file contains expanded source code) Step 2: Compilation: compiler compiles pre-processed source code into assembly code for the specific processor (gcc –S hello.i) Step 3: Assembly: Assembler converts assembly code into machine code in object file hello.o (as –o hello.o hello.s) Step 4: Linker: The linker links the object code with the library code to produce executable hello (ld –o hello hello.o ... libraries...) Compilation Assembly code (.S) Assembler Machine code (.o) Linking executable

14 Compilation with gcc gcc options can be used to determine how far to go in build process gcc –c hello.c –o hello.o machine code in file hello.o gcc –E hello.c –o hello.i preprocessed file in hello.i source code (.c, .h) Preprocessing -E Include header, expand macro (.i) Compilation -S Assembly code (.S) Assembler -o : output Step 1: Pre-processing: includes the headers (#include .h files) and expands the macros (#define) >> cpp hello.c > hello.i (hello.i file contains expanded source code) Step 2: Compilation: compiler compiles pre-processed source code into assembly code for the specific processor (gcc –S hello.i) Step 3: Assembly: Assembler converts assembly code into machine code in object file hello.o (as –o hello.o hello.s) Step 4: Linker: The linker links the object code with the library code to produce executable hello (ld –o hello hello.o ... libraries...) -c Machine code (.o) Linking executable

15 Build Summary Preprocessing: 1st pass of C compilation
processes include files & macros Compilation: takes preprocessed code and generates assembly code (.S) Assembly: produces object file (.o) Linking: takes all object files, libraries and combines to get executable file gcc flags: indicate which steps to carry out #include: used to access function definitions outside of source code file. Paste in contents of <stdio.h> at location of #include -Wall : option means compiler will warn you about legal but suspicious constructs – helps you catch bugs -E: only preprocess (produces processed file with included files copied and pasted in, comments stripped out) -S: only preprocessor and compiler (translated to assembly, produces .S file) -c: goes through preprocessing, compiling and assembler (so translates assembly to object file for specific CPU, produces .o file)

16 Some Tools

17 gdb: command line debugger
Useful commands break linenumber  create breakpoint at specified line run  run program c  continue execution step  execute next line or step into function quit  quit gdb print expression  print current value of expression l  list program Can also abbreviate: b for break, r for run, p for print To debug a program with gdb, it must be compiled by gcc with option -g

18 CLion: Integrated Development Environment
Free for students Install on your machine You can choose to use a different IDE You are strongly encouraged to use CLion

19 Text Editor & Command Line Compilation
Pick one... emacs vi Notepad++ (Windows) Compiler: gcc Make sure that your projects run correctly when compiled with gcc on the 64 bit ECE linux machines

20 General layout An example
C Programs: General layout An example

21 A C Program A C program contains:
comments – describe program in English include section C is small Need external libraries to do much Include header files to indicate what external code to use stdio library: contains code for reading and writing data from/to terminal, e.g., printf, puts for writing data to terminal scanf for reading data from terminal function prototypes main + other functions

22 #include macro Header files: constants, functions, other declarations
#include<stdio.h> - read contents of header file stdio.h stdio.h: standard I/O functions for console, files Other important header files: math.h, stdlib.h, string.h, time.h

23 Symbolic Constants: macro
Advantages of defining symbolic constants over using literals: Programs are easier to read & modify "Magic" numbers should not appear in programs A macro definition -- #define identifier replacement-list #define N 100 /* replaces symbol N with 100 in program */ . . . int i = N – 1; // What is the value of i? Macro definitions are handled by the C preprocessor (details in Ch. 14). If replacement-list contains operators, enclose it in parentheses. #define PROD(x, y) (x*y)/2 ... double p = PROD(8-2, 3); // what is p? Instead, use this: #define PROD(x, y) (((x)*(y))/2) Show example with magic number. macro uses preprocessor macro is essentially copy and paste. N will be replaced by replacement list throughout program.

24 Symbolic Constants: const Variable (Better than macro)
const variable is type checked by compiler. For compiled code with any modern compiler, zero performance difference between macros and constants. Examples: const int EOF = -1; const float TWO_PI = 2* ; Naming convention for constants: All cap words separated by underscores TWO_PI CONVERSION_FACTOR Just included here for comparison to #define – usually better option. Type checking FTW.

25 main and other functions
C code contained in functions function: named chunk of code that carries out some task Use functions to break large program into small, self-contained & cohesive units Reduces program complexity Increases reusability of code main most important function where execution of your program begins

26 Functions Function should carry out specific, well-defined task
C program = 1 or more functions, including main return-type name(type1 parm1, type2 parm2, ... ) { // function body }

27 main function main(): where execution begins
Simple version: no inputs, returns 0 when successful and non-zero to signal error int main() Two argument form of main(): provides access to command-line arguments int main(int argc, char *argv[]) More on this later...

28 Function Prototypes Declare functions before using
Declaration called function prototype Examples of function prototypes: int sumEm(int, int); or int sumEm(int n, int m); Prototypes for common functions in header files in C Standard Library General prototype form: return_type function_name(type1, type2, ....); typei is type of argument i arguments: local variables, values passed from caller return value: value returned to calling function when function exits

29 We are EE 312 /* Print message "We are EE 312" */
#include<stdio.h> int main() { // print text to console puts("We are EE 312!"); return 0; // 0 means success } puts(): output text to console window (stdout) and end the line String literal: enclosed in double quotes

30 We are EE 312, revised const: variable is a constant
/* Print message "We are EE 312" */ #include<stdio.h> int main() { const char msg[] = "We are EE 312!"; puts(msg); // print text to console return 0; // 0 means success } const: variable is a constant char: data type representing a single character char literals enclosed in single quotes: 'a', 't', '$' const char msg[]: a constant array of characters int return value is error code: normal exit if 0, problem if non-zero C standard: implied return of 0 at end of main message cannot be changed arrays: contiguous span of memory set aside for elements of the same type. Accessed by index: msg[0] is 'W' No String type in C – a string in C is an array of characters, with the end of the string marked with a special character '\0'

31 Example Output: The sum is 8 #include<stdio.h>
int sumEm(int, int); int main() { int x = 3; int y = 5; int sum = sumEm(x, y); printf("The sum is %i\n", sum); } int sumEm(int num1, int num2) { int theSum = num1 + num2; return theSum; Output: The sum is 8

32 Console I/O stdout, stdin: console output & input streams
char = getchar(): return character from stdin Later: scanf() puts(string): print string to stdout putchar(char): print character to stdout printf("format-string", list-of-values); string literals: text enclosed in double quotes

33 Console I/O printf format string contains conversion specifications that correspond to type of values to print: %i: print integer value %g: print floating point number in general format %s: print a string %c: print a char printf("Name: %s, favorite integer: %i\n", "Eberlein", 3); printf("13.0/5 = %g\n", 13.0/5); Output: Name: Eberlein, favorite integer: 3 13.0/5 = 2.6 More details on printf later

34 Variables, Operators and Types, OH MY!
And some other C Basics...

35 Syntax syntax: The set of legal structures and commands that can be used in a particular language. Every basic C statement ends with a semicolon ; The contents of a function occur between { and } syntax error (compiler error): A problem in the structure of a program that causes the compiler to fail. Missing semicolon Too many or too few { } braces, braces not matching misspelled function name, e.g., Printf("stuff"); ... C is case sensitive

36 Identifiers identifier: name given to item in your program
Identifiers may contain letters, digits, and underscores An identifier must begin with a letter or underscore Best to avoid identifiers that begin with an underscore for readability Legal: times10 ANSWER_IS_42 theCure Illegal: me+u 49ers side-swipe get-next-char C is case-sensitive: it distinguishes between upper- and lower-case letters in identifiers. Could use both count and Count as identifiers (but don't!)

37 Keywords The following keywords may not be used as your identifiers:
auto break case char const continue default do double else enum extern float for goto if inline* int long register restrict* return short signed sizeof static struct switch typedef union unsigned void volatile while _Bool* _Complex* _Imaginary* The following keywords may not be used as your identifiers: These are reserved words that have a special meaning to the compiler Keywords (with the exception of _Bool, _Complex, and _Imaginary) and names of library functions (e.g., printf) are written using only lowercase letters. *added in C99

38 Escape sequences escape sequence: A special sequence of characters used to represent certain special characters in a string. \t tab character \n new line character \" quotation mark character \\ backslash character Example: printf("\\hello\nhow\tare \"you\"?\\\\"); Output: \hello how are "you"?\\

39 Question How many visible characters does the following printf statement produce when run? printf("\t\nn\\\t\"\tt"); 1 2 3 4 Prints 4: n\ " t

40 Practice Program What is the output of the following printf statements? printf("\ta\tb\tc"); printf("\\\\"); printf("'"); printf("\"\"\""); printf("C:\nin\the downward spiral"); 40

41 Answer to Practice Program
Output of each println statement: a b c \\ ' """ C: in he downward spiral

42 Comments Comments increase readability of code Two forms:
ignored by compiler Two forms: /* Everything here is a comment */ // Everything to end of line is a comment added in C99 // C99

43 Datatypes The datatype of an object in memory determines the set of values it can have and what operations can be performed on it. C is a weakly typed language. allows implicit conversions forced (possibly dangerous) casting

44 C's built-in types primitive types: simple types for numbers, characters C++ also has object types, which we'll talk about later Name Description Examples int integers (up to ) 42, -3, 0, double real numbers (up to 10308) 3.1, , 9.4e3 char single text characters 'a', 'X', '?', '\n' We're basically going to manipulate letters and numbers. We make the integer / real number distinction in English as well. We don't ask, "How many do you weigh?" or, "How much sisters do you have?" Part of the int/double split is related to how a computer processor crunches numbers. A CPU does integer computations and a Floating Point Unit (FPU) does real number computations. Why does Java separate int and double? Why not use one combined type called number? 44

45 Built-in Data Types in C
type: a category or set of data values constrains operations that can be performed on data Numeric types Integer Examples: int (signed by default): Typically 4 bytes leftmost bit indicates sign in two's complement format Range: -231 to 231-1 unsigned int Range: 0 to 232-1 long char: 1 byte 'A', '7' Floating point float: single point precision (typically 4 bytes) double: double point precision (typically 8 bytes) long double: extended precision You have limited control over how much memory is used. int may be natural word size on specific computer. Standard is 32 bits. For maximum portability, usually use int. If you need to guarantee 32 bits, use: int32_t

46 Typical Integer Value Ranges
Data Type Smallest Value Largest Value 16 bits short int -32,768 32,767 unsigned short int 65,535 32 bits int -2,147,483,648 2,147,483,647 unsigned int 4,294,967,295 long int unsigned long int Talk about integer overflow, i.e., number too large to store as specified type. Integers use 2's complement representation. Assume we have 4 bits to store an integer. 0111 (7) +0001 (1) 1000 (-8) Adding resulted in overflow – the result was too large to store in the given representation. Actual size of integer types varies by implementation Standard provides minimum sizes for data types, and requirements about relative size: char: at least one byte short and int: at least 2 bytes long: at least 4 bytes long long: at least 8 bytes Size restrictions: sizeof(long long) >=sizeof(long) >= sizeof(int) >= sizeof(short) >= sizeof(char)

47 Integer Overflow Result of arithmetic operation on integers outside range of values that can be represented Yields incorrect results See ch 7 for more details

48 Integer Literals Three formats:
Integer literal: numeric value that cannot be altered during program execution Three formats: decimal (base 10, digits 0-9, must not begin with 0) 15, , hexadecimal (base 16, digits 0-9,a-f – must begin with 0x) 0xf, 0xfF, 0xFFF hexadecimal digits may be in upper or lower case, 0xFf or 0xff or 0xFF octal (base 8, digits 0-7, must begin with 0) 017, ,

49 Fixed-Width Integer Types
Enhance portability since sizes of integer types vary with implementation Included in C99 standard Very useful in embedded systems where hardware only supports some types Defined in inttypes.h and stdint.h header files intN_t: in interval [INTN_MIN, INTN_MAX] uintN_t: in interval [0, UINTN_MAX]

50 Floating Point Types (approximate real numbers)
Capable of representing fractional numbers Numbers are stored in 3 parts: Sign bit ( + / -) Exponent (10n, number of bits  size) Fraction (number of bits  precision)

51 Floating Point Literals
e e e e-1 Must contain decimal point – exponent is optional Fixed point notation or scientific notation Default: stored as double precision numbers F or f, L or l can be used to force storage format IEEE Standard 754 Floating Point Characteristics Precision (# bits) Smallest Value (+) Largest Significance single (32) 1.17x10-38 3.40x1038 Up to 6 digits double (64) 2.22x10-308 1.79x10308 Up to 15 digits double precision: 1 sign bit, 11 bits for exponent, 53 bits for mantissa On most systems, the double type corresponds to double precision quadruple (128) × × Up to 34 digits

52 Floating Point Types float: often IEEE 754 single-precision FP format
double: often IEEE 754 double-precision FP long double: might be IEEE 754 quadruple-precision FP format could be the same as double Sizes vary by implementation Relative size restrictions: sizeof(long double) >= sizeof(double) >= sizeof(float)

53 Data Type Sizes types are different sizes, depending on platform
How do you know? C standard library: limits.h // ranges for integer types (including char) float.h // ranges for floats and doubles Example: Write a program that prints the max and min values for int and float, as well as the size in bytes of both types Why is it this way? When C created, most machines 8-bit. Now most machines 32 or 64 bit. C can adapt over time since the sizes of data types not specified. int: INT_MAX, INT_MIN, sizeof(int)  print with %zu float: FLT_MAX, FLT_MIN, sizeof(float) double: DBL... char: CHAR... long: LNG... short: SHRT

54 Expressions expression: A combination of values and / or operations that results (via computation) in a value. Examples: * 5 (7 + 2) * 6 / 3 42 "Hello, world!" The simplest expression is a literal value. A complex expression can use operators and parentheses.

55 Arithmetic operators operator: Combines multiple values or expressions. + addition - subtraction (or negation) * multiplication / division % modulus (a.k.a. remainder) As a program runs, its expressions are evaluated. 1 + 1 evaluates to 2 printf("%d", 3 * 4); prints 12 How would we print the text 3 * 4 ?

56 Integer division with /
When we divide integers, the quotient is also an integer. 14 / 4 is 3, not 3.5 4 ) ) ) 1425 54 21 More examples: 32 / 5 is 6 84 / 10 is 8 156 / 100 is 1 Dividing by 0 causes an error

57 Integer remainder with %
The % operator computes the remainder from integer division. 14 % 4 is 2 218 % 5 is ) ) Applications of % operator: Obtain last digit of a number: % 10 is 7 Obtain last 4 digits: % is 6489 See whether a number is odd: 7 % 2 is 1, 42 % 2 is 0 What is the result? 45 % 6 2 % 2 8 % 20 11 % 0 What is 8 % 20? It's 8, but students often say 0. 57

58 Question What does each expression evaluate to? 13 % 5 5 % 13 30%5
1017 % (12 % 100)

59 Order of Operations Order of operations operator evaluation direction
+, - (unary) right to left *, /, % left to right +, - (binary) left to right =, +=, -=, *=, /= right to left Use parentheses to change order

60 Remember PEMDAS? precedence: Order in which operators are evaluated.
Generally operators evaluate left-to-right is (1 - 2) - 3 which is -4 But * / % have a higher level of precedence than * 4 is 13 6 + 8 / 2 * 3 * 3 is 18 Parentheses can force a certain order of evaluation: (1 + 3) * 4 is 16 Spacing does not affect order of evaluation 1+3 * 4-2 is 11

61 Precedence examples 1 * 2 + 3 * 5 % 4 \_/ | 2 + 3 * 5 % 4
\_/ | * 5 % 4 \_/ | % 4 \___/ | \________/ | 1 + 8 / 3 * 2 - 9 \_/ | * 2 - 9 \___/ | \______/ | \_________/ | Ask the students what 15 % 4 and 8 / 3 are, since the answers are non-obvious.

62 Precedence questions What values result from the following expressions? 9 / 5 695 % 20 7 + 6 * 5 7 * 6 + 5 248 % 100 / 5 6 * / 4 (5 - 7) * 4 6 + (18 % ( )) Answers: 1 15 37 47 9 16 -8 62

63 Real numbers (type double)
Examples: , , e17 Placing .0 or . after an integer makes it a double. Or use an explicit type cast: x = (double) 65; If you want type float: 6.022f, -42.0f The operators + - * / () all still work with double. / produces an exact answer: / 2.0 is 7.5 Precedence is the same: () before * / before + - Point out that it's odd for 42.0 to be considered a real number, but it is. Also point out that the 2.143e17 is scientific notation and means (2.143 * 10^17). 63

64 Precision in floating-point numbers
The computer internally represents real numbers in an imprecise way. Terminating base 10 decimals may not be terminating in base 2 Terminating base 2 number may not be represented exactly due to type restrictions Rounding error: error introduced by calculations on approximations More on these issues in ch. 7 Real number line is continuous/dense/infinite Floating-point number representation line is discrete, sparse, finite A group of real numbers are represented by the same fp number (approximation)

65 Mixing types When int and double are mixed, the result is a double.
The conversion is per-operator, affecting only its operands. 7 / 3 * / 2 \_/ | * / 2 \___/ | / 2 \_/ | \________/ | 3 / 2 is 1 above, not 1.5. / 3 * / 4 \___/ | * / 4 \_____/ | / 4 \_/ | \_________/ | \______________/ | (not 9!)

66 Variables variable: A piece of the computer's memory that is given a name and type, and can store a value. Like preset stations on a car stereo, or cell phone speed dial: Steps for using a variable: Declare it - state its name and type Initialize it - store a value into it Use it - print it or use it as part of an expression 66

67 Declaration variable declaration: Sets aside memory for storing a value. Variables must be declared before they can be used. Syntax: <type> <name>; int x; double myGPA; x myGPA

68 Assignment assignment: Stores a value into a variable. Syntax:
The value can be an expression; the variable stores its result. Syntax: <name> = <expression>; int x; x = 3; // or int x = 3; double myGPA; myGPA = ; //or double myGPA = 3.25; x 3 myGPA 3.25

69 Declaration/initialization
A variable can be declared/initialized in one statement. Syntax: <type> <name> = <expression>; int x = (11 % 3) + 12; double myGPA = 3.95; x 14 myGPA 3.95

70 Using Variables Once given a value, a variable can be used in expressions: int x = 3; printf("%d\n", x); // x is 3 printf("%d\n", 5 * x – 1); // 14 You can assign a value more than once printf("%d here\n", x); // 3 here x = 4 + 7; printf("Now x is %d\n", x); // Now x is 11

71 Swapping Contents of Two Variables
Output? int x = 12; int y = 32; x = y; y = x; printf("%d \t %d\n", x, y); int t = x; y = t; printf("%d \t %d \t %d\n", x, y, t); Need temporary storage for this to work...

72 Assignment and Types A variable can only store a value of its own type. int x = 2.5; // WARNING: incompatible types An implicit conversion is made. x is set to 2 An int value can be stored in a double variable. The value is converted into the equivalent real number. double myGPA = 4; double avg = 11 / 2; Why does avg store 5.0 and not 5.5 ? myGPA 4.0 x assigned value 2. Compiler warns that you did an implicit conversion in which information is lost. No problem to implictly convert an int (4) to type double – no information lost. 11/2 is integer division - produces 5, then 5 is converted to double 5.0. avg 5.0

73 Assignment The value of the statement v = e; is the value of v after the assignment Assignments can be chained together: i = j = k = 0; The = operator is right associative, so this statement is equivalent to i = (j = (k = 0)); The assignment operator may appear inside of any expression: i = 1; k = 1 + (j = i); // what is k? Don't do this! Bad style. Hurts readability.

74 Assignment Operators += -= *= /= %=
+= -= *= /= %= x += 3; // shorthand for x = x + 3; x *= x + 2; // shorthand for x = x * (x+2); i = 6; j = 2; i += j; // i is 8 i += 3*j + 2; // what is i?

75 typedef: re-naming types
typedef adds new name for existing type does not create new types Example: typedef int milesPerHour; milesPerHour currentSpeed; struct thisStruct { int value1; double value2; }; struct thisStruct s; typedef struct thisStruct greatNewType; greatNewType s2; Can't be combined with prefixes like unsigned. For example, this won't work: unsigned milesPerHour time; // compiler error long milesPerHour howFast; // error struct: collection of heterogeneous types – can be treated as a unit structure: May increase portability, so if I need to change milesPerHour to long because on some machine int is only 16 bits, this is helpful.

76 sizeof operator Returns size of operand in bytes
Return type is size_t (implementation-defined unsigned integer type) Print returned value using %lu or %zu Example: printf("Size of int: %zu\n", sizeof int); printf("Size of double: %lu\n", sizeof(double)); Output: 4 8


Download ppt "C Basics Topic 2."

Similar presentations


Ads by Google