Variables and Constants
E N D
Presentation Transcript
Variables • Variables represent names of memory locations during program execution. • Data values processed in the program are stored in memory locations and referenced through variables.
Rules of Naming Variables • A variable name is a sequence of characters each of which is chosen from the following: letters a b...z A B…Z digits 0 1…9 underscore _ • A variable name must start with either a letter or an underscore. • A variable cannot be a reserved word such as int, float double, if, switch … • The length of a variable name is not limited, although some compilers limit it to 32 characters • C/C++ is case sensitive: sum≠SUM≠Sum≠sUM
Examples of ValidVariable Names X Abc Sum Sum_5 Sum_of_values _x10 X245 a29bc56H INT Float
Examples of InvalidVariable Names if 4x1 Value? double x>y 19 a-b A* Student score
Declaring Variables • Any variable must be declared (defined) before it can be used in the program. • The same variable cannot be defined more than once within the same block • The general form of a variable declaration: data_type variable_name ; • Variables of the same type can be defined in one declaration: data_type var_name1 , var_name2 , … , var_namen;
Examples of Declaring Variables int W; // allocates 2 bytes for w int j=2; int A, B, C; int D, E=8, F, G=-600; float x, y=9.7; char z=‘L’; double L; long r, s=786543, t;
Example: A programContaining Invalid Declarations #include <iostream.h> void main(){ int x 1; double a; char a; char C=“C”; Float y; long c;d; }
Constants • A constant is a named value • Example #define SIZE 100 #define PIE 3.14 • A constant cannot be reassigned a value. The following are invalid: SIZE=200; PIE=PIE+2.5; • The compiler replaces all occurrences of a constant by its value
Example #define A 10000 void main(){ int X=A; int Y=A; int X[A]; for(int k=1; k<=A; k++) cout<<k; } Is equivalent to void main(){ int X=10000; int Y=10000; int X[10000]; for(int k=1; k<=10000; k++) cout<<k; }