Variables in C Declaring , Naming, and Using Variables
Using Variables You may declare variables in C. The declaration includes the data type you need. Examples of variable declarations: int meatballs ; float area ;
Declaring Variables When we declare a variable: space in memory is set aside to hold that data type That space is associated with the variable name Visualization of the declaration int meatballs ; meatballs FE07
Legal Variable Names Variable names in C must be valid identifiers Consists of letters, digits and underscores. May be as long as you like, but only the first 31 characters are significant. May NOT begin with a number May not be a C keyword
Naming Conventions Begin variable names with lowercase letters Use meaningful identifiers Separate “words” within identifiers with underscores or mixed upper and lower case. Example: surfaceArea surface_Area or surface_area Be consistent !!
Naming Conventions (continued) Use all uppercase for symbolic constants ( #define ) Example: PI (#define PI 3.14159 ) Function names follow the same rules as variables
Case Sensitive C is case sensitive It matters whether something is upper or lower case Example: area is different than Area which is different than AREA
More About Variables C has 3 basic predefined data types Integers int, long int, short int, unsigned int Floating point numbers float, double Characters char
Initializing Variables Variables may be initialized int x = 7; float y = 5.9; char c = ‘A’; Do not “hide” the initialization put initialized variables on a separate line a comment is probably a good idea int y = 6; /* feet per fathom */ NOT int x, y = 6, z;
Keywords in C auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while
Which Are Legal Identifiers ? AREA area_under_the_curve 3D num45 Last-Chance #values x_yt3 pi num$ %done lucky***
Declarations and assignments wreck.c inches #include <stdio.h> main ( ) { int inches, feet, fathoms ; fathoms = 7 ; feet = 6 * fathoms ; inches = 12 * feet ; } feet fathoms fathoms 7 feet 42 inches 504
wreck.c (cont’d) main ( ) { printf (“Its depth at sea: \n”) ; printf (“ %d fathoms \n”, fathoms) ; printf (“ %d feet \n”, feet); printf (“ %d inches \n”, inches); } %d is a place holder - indicates that the value of the integer variable is to be printed in decimal form (rather than binary or hex) at that location.
Floating point numbers Are numbers that can contain decimal points. What if the depth were really 5.75 fathoms ? ... Our program, as it is, couldn’t handle it. We can declare floating point variables like this : float fathoms ; float feet ;
Floating point version of wreck.c (works for any depth shipwreck) #include <stdio.h> main ( ) { float fathoms, feet; printf (“Enter the depth in fathoms : ”); scanf (“%f”, &fathoms); feet = 6.0 * fathoms; printf (“She’s %f feet down.\n”, feet); }