Presentation is loading. Please wait.

Presentation is loading. Please wait.

ECE 103 Engineering Programming Chapter 10 Variables, AKA Objects Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103.

Similar presentations


Presentation on theme: "ECE 103 Engineering Programming Chapter 10 Variables, AKA Objects Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103."— Presentation transcript:

1 ECE 103 Engineering Programming Chapter 10 Variables, AKA Objects Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed by Professor Phillip Wong @ PSU ECE

2 Syllabus What’s This Blue Code? Naming Variables Declaring Variables Assigning Values to Variables Read-only Variables

3 2 What’s This Blue Code? void main() { // main #ifdef Apollo printf( " C program on Apollo.\n" ); #else # undef Apollo // o.k. to undef what isn't defined # ifdef IBMPC printf( " C program on IBMPC.\n" ); # else # ifdef Sun printf( " C program on Sun.\n" ); # else printf( " Don't know what this runs on.\n" ); # endif } //end main

4 3 Naming Variables Variables store data for use by a program Fashionable to call “variables” instead: “objects” Any C program variable has a name, type, scope – and other attributes, e.g. const-- that uniquely identifies it The datum stored in a variable is called its value A variable’s value may be modified during execution Some variables persist during the whole program life; others come and go automatically as functions come to life; yet others appear dynamically –on heap

5 4 Identifiers –e.g. names of variables-- can contain:  Letters (uppercase A-Z and lowercase a-z)  Digits (0-9)  Underscore _ Must start with letter; underscore counts as letter Note:A leading underscore is typically reserved for system variables. Use a letter instead At least 31 characters are significant C variable names are case-sensitive

6 5 C keywords cannot be used as variable names Reserved keywords: † Is only reserved in C99 autoenumrestrict † unsigned breakexternreturnvoid casefloatshortvolatile charforsignedwhile constgotosizeof_Bool † continueifstatic_Complex † defaultinline † struct_Imaginary † dointswitch doublelongtypedef elseregisterunion C99

7 6 Hints for naming variables:  Accurately describe what the variable represents  Choose a name just long enough to be clear  Avoid names that are too short unless necessary  Be consistent in your naming convention Common styles for multi-word identifiers: federal_tax_rate ← underscores Federal_Tax_Rate federalTaxRate ← camel case FederalTaxRate

8 7 Example: meanvalue2, mEaNvAlUe2, and MeanValue2 are all different names. Sample Variable NameValidComment x Yes Generally not best naming convention meanvalue2 Yes mEaNvAlUe2 MeanValue2 Mean_Value_2 8ball Wait4It$ double ABCDEFGHIJKLMNOPQRSTUVWXYZ12345abc ABCDEFGHIJKLMNOPQRSTUVWXYZ12345def Yes No Spaces are not allowed Underscores are fineYes NoFirst character must be a letter No $ is illegal character No Cannot use C keyword for variable name Yes At least 31 characters significant Maybe Depends on number of significant chars

9 8 Declaring Variables Variables must be declared in C, else cannot be used A declaration specifies the name, type, scope, and storage attribute of variable  Is the selected type appropriate for representing the data?  Do you need to consider the possibility of overflow?  For floating point, does the type have enough precision/range?  Is memory available? Once declared, a non-static variable has an unknown value until explicitly initialized Static objects are initialized to 0 by default If a variable must have a particular starting value, then initialize it explicitly before using it!

10 9 Syntax: type varname1, varname2, …; Example: int lower, upper, step; float x; double y, z[500]; Variables of the same type can also be declared on separate lines. Example: int lower;/* Lower bound of range */ int upper;/* Upper bound of range */ int step;/* Step size */

11 10 Assigning Values to Variables Assignment operator is a single equal sign = varname = expression; Example: speed_of_light = 2.99792458e8; Do not confuse = (assignment) with == (comparison). Example: x = 5; x == 5; Stores the number 5 in variable x.Compares value of variable x to the number 5 for equality.

12 11 Variables can be initialized in or after declaration Example: float delta; /* unknown initial value */ delta = 1.5e-6f; /* now equals 1.5e-6 */ Example: int count;/* All are uninitialized */ int w; float factor; count = 5;/* Now initialized */ w = 3; factor = 2.0f * (count + w);

13 12 Variables can be initialized during declaration: type varname = initial_expression; Example: char InChar = 'A'; float delta = 1.5e-6f;

14 13 In C90, variable declarations must appear at the start of a block and before other code statements Cannot arbitrarily mix variable declarations and code Example: double pi = 3.141592654; double w, f = 100; w = 2*pi*f; double x; x = w + pi / 6.0; This declaration will cause a compiler error. In C90, double x; must go before w = 2*pi*f;

15 14 Order of Variable Declarations and Code C99 allows variable declarations to be mixed with code. This allows a variable to be declared closer to where it is first used. /* C90 version */ #include int main (void) { int x = 1, y = 3, z, A[2]; z = x + 7; A[0] = 36; A[1] = z; printf("%d\n", y); return 0; } // C99 version #include int main (void) { int x = 1, z; z = x + 7; int A[2]; A[0] = 36; A[1] = z; int y = 3; printf("%d\n", y); return 0; } C99

16 15 Read-Only Variables With a standard declaration, the value stored in a variable can be changed at will To declare a variable whose contents can be read but not changed, use the const modifier: const type varname = value; A variable that is const must be assigned its value when it is declared

17 16 Example: const int answer_to_the_ultimate_question = 42; Example: double g = 9.81; /* standard declaration */ g = 1.6; /* Can change it */ Example: const double g = 9.81; /* Make it read-only */ g = 1.6; /* Causes compiler error */ Example: /* This is a constant string */ const char * msg = "PSU"; printf("Message: %s\n", msg);

18 17 Arrays, Initial Coverage An array in C is a collection of 1 or more elements of all the same type Known by one name, the array name Usable like any scalar variable But selected by an operation called “indexing” With the low index, AKA the name of the first element, being an integer value of 0 And the last element being of index “number_of_elements – 1”

19 18 Arrays, Initial Coverage Sample #define MAX 4 int count1;// declaration w/o initialization int count2 = 9;// scalar object with initial value 9 int mat1[ 4 ];// 4 elements hard coded bounds 0..3 int mat2[ MAX ];// 4 elements properly expressed int mat3[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23 }; int mat4[ 9 ] = { 1, 1, 1, 2, 2, 2, 3, 3, 3 };... mat3[ 2 ] = mat4[ I ] + mat3[ 0 ];


Download ppt "ECE 103 Engineering Programming Chapter 10 Variables, AKA Objects Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103."

Similar presentations


Ads by Google