variables and expressions
DESCRIPTION
This describes the usage of Variables and Expressions in C ProgrammingTRANSCRIPT
Overview of C
•Data Types
•Constants
•Variables
•Expressions
•Operators
C TOKENS
C Tokens
Constants
Special symbols
Identifiers
Operators
StringsKey words
floatwhile
+ - * ,
-15.4100
“ABC”“hello”
{}[]
mainamount
Keywords and Reserved Identifiers
Keywords are the vocabulary of C. Because they are special to C, you can't use them as identifiers, for example, or as variable names.
ISO/ANSI C Keywords
auto enum restrict unsigned
break extern return void
case float short volatile
char for signed while
const goto sizeof _Bool
continue if static _Complex
default inline struct _Imaginary
do int switch
double long typedef
else register union
Reserved identifiersThere are other identifiers, called reserved identifiers,
that you shouldn't use.
They don't cause syntax errors because they are valid names. However, the language already uses them or reserves the right to use them, so it could cause problems if you use these identifiers to mean something else.
Reserved identifiers include those beginning with an underscore character and the names of the standard library functions, such as …
printf(), main etc
User defined type declarationThe typedef facility is an advanced data feature that enables you to
create your own name for a type. typedef type identifier;It is similar to #define in that respect, but with three differences:
Unlike #define, typedef is limited to giving symbolic names to types only and not to values.
The typedef interpretation is performed by the compiler, not the preprocessor.
Within its limits, typedef is more flexible than #define.
In the above syntax type refers to existing data type and identifier refers to the “new” name given to that data type
Ex: typedef int marks;
We use typedef for to improve interpretation of programmer. Mostly in case of structures, declaring variables is easier if we typedef the structure type.
Note:When using typedef, bear in mind that it does not create new types; instead, it just creates convenient labels
Enumerated data type
Another user-defined data type is enumenum identifier {value1, value2, value3..};
The identifier above is user defined data type which can be used to declare variables that can have one of the values enclosed within the braces ( Known as enumeration constants. )
Ex: enum color { red, blue, white, gray, silver};enum color nano1, nano2;
nano1 and nano2 are variables of type color and they can have only above mentioned 5 colors.
Declaration of storage classVariables in C can have not only data type, but also
storage class that provides information about their location and visibility.
The storage class decides the portion of program ( SCOPE ) and storage duration of the variable in a program. We mainly have 4 storage classes.
_______________________________________Storage class Meaning
auto : Local variable known only to the function or block in which it is declared ( default is auto ).
static : Local variable which exists and retains its value even after control is transferred to calling functin.
extern: Global variable known to all functions in the file.register: Local variable which is stored in register memory to
improve speed of execution
sizeof() operatorsizeof will return the number of bytes reserved for a variable
or data type. ( custom or user defined ).
The following code snippets shows sizeof returning the length of a data type.
printf("%d", sizeof(int)); // o/p is 2printf(“%d”, sizeof(“hello”); //o/p is 6Note: A string ends with a null character. So size of
string is number of characters + 1.
Int x[5];Int size_of_array = sizeof(x);printf(“%d”,size_of_array); // o/p is 10
// Similary size of user defined data types like structures return their respective sizes.
Defining Conversion Characters
Inside many of the printf()s that you have seen there were several conversion characters. These special characters tell printf() exactly how the data (following the characters) are to be interpreted.
Conversion Character Modifiers
All floating-point numbers print (using %f) with too many decimal places for most applications. What if you want to print only dollars and cents (two decimal places), or print an average with a single decimal place?
The following printf() prints the number 456 in five positions (with two leading spaces)
printf("%5d", 456); // 456
If you put a minus sign before the width specifier, C left-justifies the number inside the width .
printf(''%d%d%d \n", 456, 456, 456); //456456456 printf("%-5d%-5d%-5d \n", 456, 456, 456); //456 456 456 printf("%-7d%-7d%-7d \n", 456, 456, 456); //456 456 456
The format of the floating-point width specifier is %width.decimalsf
Ex:printf("%6.2f", 134.568767); // o/p is 134.56
Similarly scanf can be used to receive truncated value. // In case of Integer input, leading digits are considered
Ex: scanf(“%2d”,a) // If 123 is input for a, only 12 will be read into it.
Note: printf() never truncates a integer value while printing.
Constants and variablesSometimes you need to use a constant in a program. Example value
of Pi is 3.14 which is same through out the program.
Constants are defined by preprocessor directive # define.#define PI 3.14159 .
Where ever in the code PI is encountered, it’s replaced with it’s value during preprocessing stage
The const Modifier
There is a second way to create symbolic constants—using the const keyword to convert a declaration for a variable into a declaration for a constant:
const int MONTHS = 12; // MONTHS a symbolic constant for 12
This makes MONTHS into a read-only value. That is, you can display MONTHS and use it in calculations, but you cannot alter the value of MONTHS.
Operators C uses operators to resolve arithmetic and logical
expressions.
Operators in C
Arithmetic Operator precedence
Operator precedence provides vital rules for determining the order of evaluation in an expression
Relational OperatorCompare two values Result : true or false ( 0 or 1 )Operator
, , , , ,
precedence
a > b + c ===> a > (b + c) b == x < y ===> b == (x < y)
Conditional Operators• Conditional Logical Relationship of two
operands• Operators ! , && , || are called Logical
not, AND and OR respectively• The operands are either zero or one (any
non zero value is also treated as one)
a < b && b < c a < b && b < c1 2
3
O/P is either 0 or 1
Truth Table
Ex : a= 13, b=0
a && b will return 0 , a || b will return 1
Increment & Decrement Operator• Operator
++, --– Prefix operator
– Postfix operator
– Cannot use at expression, only at variable level– Cannot apply at real type data
n = 1; x = ++n; // x=2, n=2
n = 1; x = ++n; // x=2, n=2
n = 1; x = n++; // x=1, n=2
n = 1; x = n++; // x=1, n=2
(a + b)++ // error (a + b)++ // error
Bitwise Operator• Operator
– &, |, <<, >>, >>>• Bitwise AND
– 10012 & 00112 = 00012
• Bit OR
– 10012 | 00112 = 10112
– Operand should be integer type– Precedence
Operator PrecedenceOperator Precedence
~<< >> >>>
&^|
(H)
(L)
Bitwise Operator
• Bitwise Shift Operator – Shift left ( << )
– Shift right ( >> )
– Ex: 1000 ( Binary 8) >> 2 gives 10 ( Binary 2)
– Ex: 111 ( Binary 7) << 2 gives 11100 ( binary 28)
x << y = x * 2y x << y = x * 2y
x >> y = x / 2y x >> y = x / 2y
The Conditional Operator
• Ternary Operator– Expr1 ? Expr2 : Expr3 (3 Terms
Operator)
Nested Ternary operator
max = x > y ? x : y ; max = x > y ? x : y ; if (x > y) max = x; else max = y;
if (x > y) max = x; else max = y;
m = a > b ? (c > a ? c : a) : (c > b ? c : b) ; m = a > b ? (c > a ? c : a) : (c > b ? c : b) ;
Assignment Operators
• Operator = can be used with combination of– Arithmetic operator : + - * / %– Bitwise operator : & | ^ << >>
>>>
Expr 1 = Expr 1 op Expr2Expr 1 = Expr 1 op Expr2 Expr1 op= Expr 2 Expr1 op= Expr 2
x = x * y + 1; x = x * y + 1; x *= y + 1; x *= y + 1;
x = x * (y+1)x = x * (y+1)
sum = sum + i ; sum = sum + i ; sum += i ; sum += i ;
Operator Precedence
Operator Precedence
() [] . ! ~ ++ -- + - (Data Type) * / % + - << >> >>> < <= > >= instance == != & ^ | && || ? : = += -= *= /= %= &= ^= |= <<= >>= >>>=
(High)
(Low)
Type Conversion or type castingSize Direction of Data Type
Widening Type Conversion (Casting down)Smaller Data Type Larger Data Type
Narrowing Type Conversion (Casting up) Larger Data Type Smaller Data Type
Who will convert the type? Implicit type conversion
Carried out by compiler automatically Explicit type conversion
Carried out by programmer using casting
Implicit type casting
• Widening Type Converstion Implicit conversion by compiler
automatically
– Examples :byte -> short, int, long, float, double
short -> int, long, float, doublechar -> int, long, float, double
int -> long, float, doublelong -> float, double
float -> double
byte -> short, int, long, float, doubleshort -> int, long, float, doublechar -> int, long, float, double
int -> long, float, doublelong -> float, double
float -> double
Explicit type casting
• Narrowing Type ConversionProgrammer should describe the conversion
explicitly
– Examples :byte -> char
short -> byte, charchar -> byte, short
int -> byte, short, charlong -> byte, short, char, int
float -> byte, short, char, int, longdoule -> byte, short, char, int, long, float
byte -> charshort -> byte, charchar -> byte, short
int -> byte, short, charlong -> byte, short, char, int
float -> byte, short, char, int, longdoule -> byte, short, char, int, long, float
char c='A'; short s=1; int i=2; long l=3; float f=2.1f; double d=3.2;
(1) i = (c + s); // i = ?? (int T) (char T) (short T) (short T)
(int T)
char c='A'; short s=1; int i=2; long l=3; float f=2.1f; double d=3.2;
(1) i = (c + s); // i = ?? (int T) (char T) (short T) (short T)
(int T)
char c='A'; short s=1; int i=2; long l=3; float f=2.1f; double d=3.2;
(1) s = (short) (c + i); // s = ?? (short T) (char T) (int T) (int T)
(short T)
char c='A'; short s=1; int i=2; long l=3; float f=2.1f; double d=3.2;
(1) s = (short) (c + i); // s = ?? (short T) (char T) (int T) (int T)
(short T)
Converted by Converted by compiler compiler automaticallyautomatically
Converted Converted by by programmer programmer using cast using cast operatoroperator
Floating point representationA floating-point number more or less corresponds
to what mathematicians call a real number. Example of some floating-point numbers are 2.75, 3.16E7, 7.00, and 2e–8
To represent a floating-point number in a computer, a certain number of bits (depending on the system) are set aside to hold a binary fraction. Additional bits hold an exponent.
Floating point numbers are stored in 32 bits out of which 6 digits are allocated towards precision. So if a real number is overflowing either in the integer or decimal region, we could adjust number by varying the exponent value. Also exponent notation could be used to enhance readability.
Ex: 0.000000032 can be written as 3.2e-8
An example to remembermain(){int i=5,j,k=5;j=i++ + i++; // LHS gives different o/p if it’s i=i++ + i++printf("%d %d \n",i,j); // o/p is 7 10
printf("%d %d %d",k,k++ + k++,k); //o/p is 7 11 5}
If the second printf had been…
printf("%d %d %d",k,++k + k,k++); // o/p is 7 14 5printf("%d %d %d",k,++k + ++k,k); // o/p is 7 13 5printf("%d %d %d",k,++k + k++,k); // o/p is 7 12 5printf("%d %d %d",k,k++ + k--,k); // o/p is 5 11 5printf("%d %d %d",k,k-- + k++,k); // o/p is 5 9 5
Lvalue errorIn case of expressions like ++i+++i etc the
compiler is expecting Left hand side variable to be defined properly. Only modifiable lvalues can be used on the left side of assignment operators.
So i+++i i++ +i i+++ i i++ + iSimilarly..i +++i is also permitted since i++ is same as i +
+.But… --i+++i does not define lvalue properlyi.e it cannot be treated as –-i + ++i
End of chapter…!
Evaluate as many expressions as possible and verify the o/p