Variables and literals

Similar documents
A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Work relative to other classes

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Lecture 3. More About C

Chapter 3: Operators, Expressions and Type Conversion

Computer System and programming in C

These are reserved words of the C language. For example int, float, if, else, for, while etc.

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

UNIT- 3 Introduction to C++

Fundamental of Programming (C)

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Declaration and Memory

CS313D: ADVANCED PROGRAMMING LANGUAGE

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

Review of the C Programming Language for Principles of Operating Systems

Chapter 12 Variables and Operators

C Language Summary. Chris J Michael 28 August CSC 4103 Operating Systems Fall 2008 Lecture 2 C Summary

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

EL2310 Scientific Programming

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

OBJECT ORIENTED PROGRAMMING

Unit 3. Operators. School of Science and Technology INTRODUCTION

Continued from previous lecture

Chapter 12 Variables and Operators

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

Data Types and Variables in C language

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

CSC 1107: Structured Programming

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Procedures, Parameters, Values and Variables. Steven R. Bagley

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html

Introduction to C Language

Expressions and Precedence. Last updated 12/10/18

Flow Control. CSC215 Lecture

Program Fundamentals

Fundamentals of Programming

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Computers Programming Course 6. Iulian Năstac

ME 461 C review Session Fall 2009 S. Keres

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Review of the C Programming Language

Goals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"

LECTURE 3 C++ Basics Part 2

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

printf( Please enter another number: ); scanf( %d, &num2);

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Expressions and Casting

CSI33 Data Structures

Programming. Elementary Concepts

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Java Basic Programming Constructs

Language Fundamentals Summary

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Course Outline Introduction to C-Programming

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Chapter 12 Variables and Operators

1 Lexical Considerations

ECE 122 Engineering Problem Solving with Java

Java Programming Fundamentals. Visit for more.

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Introduction to C++ with content from

2 nd Week Lecture Notes

These are notes for the third lecture; if statements and loops.

Chapter 12 Variables and Operators

Programming for Engineers Introduction to C

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Chapter 7. Basic Types

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

CMPT 125: Lecture 3 Data and Expressions

A Fast Review of C Essentials Part I

The Design of C: A Rational Reconstruction: Part 2

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Variables and Operators 2/20/01 Lecture #

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

JAVA Programming Fundamentals

1007 Imperative Programming Part II

Java Notes. 10th ICSE. Saravanan Ganesh

C: How to Program. Week /Mar/05

Structure of this course. C and C++ Past Exam Questions. Text books

C Programming Language. Microcomputer Architecture and Interfacing Colorado School of Mines Professor William Hoff

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

Maciej Sobieraj. Lecture 1

Transcription:

Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of this in the G52CFJ (C and C++) module in previous years, I have included the slides from that module here, to remind people who may not attend the demo lectures, or may forget what was said

Variables and literals #include <stdio.h> int main( int argc, char* argv[] ) { int j = 0; A literal A literal/actual value do something spectacular } return 0; // Success A variable declaration/definition Defines a variable of type int, with name j Definition: Defines what it does / creates one Declaration: Says it exists, but doesn t create it An important difference later for functions, variables and classes

Comments Comments: /* For multi-line comments */ Available in both C and C++ // For single line comments In C++ but not officially in C89 There is no official Javadoc for C/C++ i.e. /** */ for code documentation There are unofficial programs, e.g. doxygen

Braces: { } Braces {} are used in the same way as Java Create a compound statement from multiple statements e.g. for an if or for statement Extra {} can be added to make execution blocks Local variables exist for the lifetime of the block they are in (not the function) int main( int argc, char* argv[] ) { int j = 0; { int k = 3; /* k exists now */ } /* k no longer exists now */ return 0; // Success }

Basic data types

Basic Data Types The types available are what you expect: Integer types: char, short, int, long Floating point: float, double, long double No string type in C! (treat char* as string) Signed/unsigned variants of integer types Unlike in Java where they are all signed Examples: signed char sc; signed long sl; Default is signed unsigned short us; unsigned int ui; If neither signed nor unsigned stated

Sizes of types The size (in bits/bytes) can vary in C/C++ For different compilers/operating systems In Java, sizes are standardised, across O/Ss Some guarantees are given: A minimum size (bits): char 8, short 16, long 32 Relative sizes: char short int long C & C++ have an operator called sizeof() to ask how man chars big a data type is (sometimes this matters) An int changes size more than other types! Used for speed (not portability) But VERY popular! (fast) Uses the most efficient size for the platform 16 bit operating systems usually use 16 bit int 32 bit operating systems usually use 32 bit int 64 bit operating systems usually use 64 bit int

Basic Data Types - Summary Type Minimum size (bits) Minimum range of values (Depends upon the size on your platform) char 8-128 to 127 (Java chars are 16 bit!) short 16-32768 to 32767 long 32-2147483648 to 2147483647 float Often 32 Single precision (implementation defined) e.g. 23 bit mantissa, 8 bit exponent double Often 64 Double precision (implementation defined) e.g. 52 bit mantissa, 11 bit exponent long double double Extended precision, implementation defined int short varies

Declaring/defining a variable Important: Variables will NOT be initialised No default values are given in C++! Nothing MUST be initialised Values are unknown! (whatever was in memory) In Java member variables get default values and local variables MUST be initialised before use ALWAYS initialise your variables At worst, errors are then repeatable Examples: float f1 = 1.0f; // A single float int i1=4, i2=52; // Two ints

Integer literals Integer literals may be: Decimal (base 10) : default, no prefix needed Hexadecimal (base 16) : prefix 0x Octal (base 8) : prefix 0 (Not available in Java) Examples: int x = 19, y = 024, z = 0x15; char c1 = 45, c2 = 67, c3 = 0; unsigned short s = 0xff32; The compiler chooses a size based upon the size of an int and the value of the literal (e.g. char, short, int, long) You can explicitly make a literal value long (add suffix L) long l1 = 1000000000L; long l2 = 1234567890L;

Character literals Character literals mean the value of this character using the standard character set for this computer (ASCII here) char c1 = h, c2 = e, c3 = l, c4 = l, c5 = o ; A char is a number (from -128 to +127) In output functions you specify whether to show the number (%d) or the ASCII character of that value (%c) Some character literals have special meanings \t is the character which, when printed, will display a tab character \n is a character which will display as a newline Can be CR, CR+LF, depending on platform In Java \n and \r have fixed values

String literals You can have string literals: char* s1 = "This is a string literal\n"; Actually: arrays of characters, with a 0 at the end Enclose the literal in double quotes Format is same as Java: String s1 = Hello ; printf takes a char* as first parameter: printf( "Hello World!\n" ); printf( s1 ); Remember: character literals have single quotes 4, h, H, %,, @,, string literals have double quotes

Floating point literals Same as Java Double precision floating point (double): 1.0, 2.4, 1.23e-15, 9.5e4 double d = 1.34283; Single precision floating point (float): 1.0f, 2.4f, 2.9e-3f float f = 5.634f ; (note the f to say float rather than the default type of double )

Converting between types Data can be converted between types Sometimes done implicitly If compiler knows how to safely change the type e.g. char to a short, short to a long, float to a double, int to a double (same rules as Java) Sometimes it has to be done explicitly If conversion may lose data e.g. long to a short, short to a char, double to a float, float to an int (same rules as Java) Or compiler needs to confirm that it isn t an error: Are you sure?

Type casts Can explicitly change the type via a cast C version is exactly the same as in Java Put the new type inside brackets () long l = 100L; short s = (short)l; Includes signed <-> unsigned conversion unsigned int ui = (unsigned int)i; C++ also adds new types of casts Safer and better We will return to these later

The void type The void type is used to mean: No return value, e.g. void foo( int a ); No parameters, optional, (Not Java) e.g. int bar(void); Will also see later a void* You cannot create a variable of type void Some (older) compilers will not accept void But they should do if they are C89/C90/C99

Operators (same as Java)

Operators Operators will be familiar to you from Java: Arithmetic: a*b, a-b, a+b, a/b Integer division: Logical AND/OR: Comparison: a/b, a%b a && b, a b a<b, a<=b, a>b, a>=b a==b, a!=b Increment Decrement Shorthand: a++, ++a a--, --a a+=b, a-=b, a*=b, a/=b e.g. a+=b is equivalent to a = a + b

Sample Operator Precedence List Operators are evaluated in a specific order Highest operator precedence applies first Examples (highest to lowest, not complete) (), [], ++, -- Grouping, array access, post increment/decrement ++, --, *, & Pre-increment, dereference, address of (right to left) *, /, % Multiplication, division, modulus + - Addition, subtraction <, <=, >, >= Comparison Increasing precedence ==,!= Comparison: equal to, not equal to & Bitwise AND ^ Bitwise XOR Bitwise OR && Logical AND Logical OR? : Ternary conditional =, +=, -= etc Assignment and and assign (right to left)

Operator precedence matters && has higher precedence than if ( a && b c && d ) means if ( (a && b) (c && d) ) if ( a b && c d ) means if ( a (b && c) d )

Operators and precedence Operator precedence matters! Many style guides state that operator precedence should not be relied upon Makes code less readable Prone to reliability of programmer s memory I will NOT mark you down for adding unnecessary brackets (within reason) I do it where I think it aids clarity Company coding standards often require them But you need to know the precedence rules To understand code written by others An exam question may rely on them

The printf() function

The printf function Reminder: printf is declared in stdio.h #include <stdio.h> so compiler knows what it is printf will output formatted text It uses tags (starting with % ) which are replaced by the supplied parameter values, in order Examples: int i = 50; char* mystring = Displayable string ; printf( Number: %d\n, i ); printf( String: %s\n, mystring ); printf( %d %s\n, i, mystring );

More things (almost) exactly the same

Conditionals Example if statement: (same as Java!) if ( x == 4 ) printf( X is 4\n ); else printf( X is not 4\n ); Ternary conditional operator: (same as Java!) char* str = (x == 4)? X is 4\n : X is not 4\n ; printf( str ); The switch statement (same as Java!) switch( x ) { case 4: printf( X is 4\n ); break; default: printf( X is not 4\n ); break; }

Loops: same as Java Example for loop: int x = 1; for ( x = 2; x < 10 ; x++ ) { printf( X is %d\n, x); } Example while statement: int x = 12; while ( x > 4 ) { printf( X is %d\n, x ); x--; } Example do { } while statement: int x = 1; do { printf( X is %d\n, x ); x++; } while ( x < 8 );

break and continue break Already seen use in a switch Also used in loops : exit the loop continue Used in loops End this iteration of the loop i.e. Jump to the for/while control statement int i = 0; for ( ; i < 30 ; i++ ) { if ( i==5 ) continue; if ( i==10) break; printf( "%d ", i ); } What is the output:?

break and continue break Already seen use in a switch Also used in loops : exit the loop continue Used in loops End this iteration of the loop i.e. Jump to the for/while control statement int i = 0; for ( ; i < 30 ; i++ ) { if ( i==5 ) continue; if ( i==10) break; printf( "%d ", i ); } Output: 0 1 2 3 4 6 7 8 9

Aside: Function Overloading A C vs C++ difference Here C++ is like Java

Function overloading In C++ a function is identified by the types of its parameters as well as its name As it is in Java, but not in C This example is valid in C++ (not in C) int multiply( int a, int b ) {return 0;} long multiply( long a, long b) {return 0;} i.e. can have multiple functions with the same name The compiler will check the parameter types and try to find a matching function (like Java) Sometimes the types of the parameters may need to be changed to find a function Will usually be performed automatically (implicitly) as long as a conversion exists (see later)