🔵 Variables and constants are the basic data objects manipulated in a program.
🔵 Declarations list the variables to be used, and state what type they have and perhaps what their initial values are. Operators specify what is to be done with them. Expressions combine variables and constants to produces new values.
🔵 The type of an object determines the set of values it can have and what operations can be performed on it.
🔵 The ANSI standard has made many small changes and additions to basic types, and expressions. There are now signed and unsigned forms of all integer types, and notations for unsigned constants and hexadecimal character constants. Floating-point operations may be done in single precision; there is also a long double type for extended precision. String constants may be concatenated at compile time. Enumerations have become part of the langugae, formalizing a feature of long standing. Objects may be declared const, which prevents them from being changed. The rules for automatic coercions among arithmetic types have been augmented to handle the richer set of types.
🔵
There are some restrictions on the names of variables and symbolic constants.
Names are made up of letters and digits; the first character must be a letter.
The underscore "_" counts as a letter; it is sometimes useful for improving the
readability of long variable names. Don't begin variable names with underscore,
however, since library routines often use such names. Uppercase and lowercase
letters are distinct, so x and X are two different names.

🔵 Keywords like if, else, int, float, etc., are reserved: you can't use them as variable names. They must be in lower case.
🔵 We tend to use short names for local variables, especially loop indices, and longer names for external variables.
🔵 There are only a few basic data types in C:
🔵 There are a number of qualifiers that can be applied to these basic types. short and long apply to integers:
short int sh; /* short sh */
long int counter; /* long counter */
🔵 Each compiler is free to choose approporiate sizes for its own hardware, subject only to the restriction that shorts and ints are at least 16 bits, longs are at least 32 bits, and short is no longer than int , which is no longer than long.
🔵 The qualifier signed or unsigned may be applied to char or any integer. unsigned numbers are always positive or zero, and obey the laws of arithmetic modulo 2n, where n is the number of bits in the type. So, for instance, if chars are 8 bits, unsigned char variables have values between 0 and 255, while signed chars have values between -128 and 127 (in a two's complement machine).
🔵 Whether plain chars are signed or unsigned is machine-dependent, but printable characters are always positive.
🔵 The type long double specifies extended-precision floating point. As with integers, the sizes of floating-point objects are implementation-defined; float, double and long double could represent one, two or three distinct sizes.
🔵 See standard header files <limits.h> and <float.h>. ➡ limits.c and float.c
$ gcc -print-file-name=include/float.h
/usr/lib/gcc/x86_64-linux-gnu/15/include/float.h
🔵 An integer constant like 1234 is an int. A long constant is written with a terminal l (ell) or L as in 123456789L; an integer too big to fit into an int will also be taken as long. Unsigned constants are written with a terminal u or U, and the suffix ul or UL indicates unsigned long.
🔵 Floating-point constants contain a decimal point (123.4) or an exponent (1e-2) or both; their type is double, unless suffixed. The suffixes f or F indicate a float constant; l or L indicate a long double.
🔵 The value of an integer can be specified in octal or hexadecimal instead of decimal. A leading 0 (zero) on an integer constant means octal; a leading 0x or 0X means hexadecimal. For example (31)10= (037)8=(0x1f)16=(0X1F)16.
🔵 Octal and hexadecimal constants may also be followed by L to make them long and U to make them unsigned: 0XFUL is an unsigned long constant with value 15 decimal. ➡ example
🔵 A character constant is an integer, written as one character within single quotes, such as 'x'. The value of a character constant is the numeric value of the character in the machine's character set. For example in the ASCII character set the character constant '0' has the value 48, which is unrelated to the numeric value 0.
🔵 If we write '0' instead of a numeric value like 48 that depends on character set, the program is independent of a particular value and easier to read. Character constants participate in numeric operations just as any other integers.
🔵 An arbitrary byte-sized bit pattern can be specified by '\ooo' where ooo is one to three octal digits (0...7) or by '\xhh' where hh is one or more hexadecimal digits (0...9, a...f, A...F). ➡ example
💡
ترکیب \xhh یک escape sequence واحد است و فقط برای نوشتن یک کاراکتر است.
#define VTAB '\013' /* ASCII vertical tab */
#define BELL '\007' /* ASCII bell character */
or
#define VTAB '\xb' /* ASCII vertical tab */
#define BELL '\x7' /* ASCII bell character */

🔵 The character constant '\0' represents the character with value zero, the null character. '\0' is often written instead of 0 to emphasize the character nature of some expression, but the numeric value is just 0.
🔵 A constant expression is an expression that involves only constants. Such expressions may be evaluated during compilation rather than run-time, and accordingly may be used in any place that a constant can occur, as in
#define MAXLINE 1000
char line[MAXLINE+1];
or
#define LEAP 1 /* in leap years */
int days[31+28+LEAP+31+30+31+30+31+31+30+31+30+31];
🔵 A string constant, or string literal is a sequence of zero or more characters surounded by double quotes, as in
"I am a string"
or
"" /* the empty string */
🔵 the same escape sequences used in character constants apply in strings; \" represents the double-quote character.
🔵 String constants can be concatenated at compile time. This is useful for splitting long strings across several source lines.
"hello," " world" ≡ "hello, world"
🔵 Technically, a string constant is an array of characters. The internal representation of a string has a null character '\0' at the end, so the physical storage required is one more that the number of characters written between the quotes. This representation means that there is no limit to how long a string can be, but programs must scan a string completely to determine its length.
🔵 strlen and other string functions are declared in the standard header <string.h>.
🔵 Be careful to distinguish between a character constant and a string that contains a single character: 'x' is not the same as "x". The former is an integer, used to produce the numeric value of letter x in the machine's character set. The latter is an array of characters that contains one character (the letter x) and a '\0'.
🔵 An enumeration constant is a list of constant integer values, as in
enum boolean { NO, YES };
The first name in an enum has value 0, the next 1, and so on, unless explicit values are specified.
If not all values are specified, unspecified values continue the progression from the last specified value, as in the second of these examples:
enum escapes { BELL = '\a', BACKSPACE = '\b', TAB = '\t',
NEWLINE = '\n', VTAB = '\v', RETURN = '\r' };
enum months { JAN = 1, FEB, MAR, APR, MAY, JUN,
JUL, AUG, SEP, OCT, NOV, DEC };
/* FEB is 2, MAR is 3, etc. */
🔵 Names in different enumerations must be distinct. Values need not be distinct in the same enumeration.
🔵 Enumerations provide a convenient way to associate constant values with names, an alternative to #define with the advantage that the values can be generated for you.
🔵 Although variables of enum types may be declared, compilers need not check that what you store in such a variable is a valid value for the enumeration. Neverthless, enumeration variables offer the chance of checking and so are often better than #defines. In addition, a debugger may be able to print values of enumeration variables in their symbolic form.
➡ example of enumeration constants
🔵 All variables must be declared before use, although certain declarations can be made implicitly by context. A declaration specifies a type, and contains a list of one or more variables of that type.
int lower, upper, step;
char c, line[1000];
A variable may also be initialized in its declaration. If the name is followed by an equal sign and an expression, the expression serves as an initializer:
int limit = MAXLINE+1;
float eps = 1.0e-5;
int i = 0;
char esc = '\\';
🔵 If the variable in question is not automatic, the initialization is done once only, conceptually before the program starts executing, and the initializer must be a constant expression.
🔵 An explicitly initialized automatic variable is initialized each time the function or block it is in is entered; the initializer may be any expression.
🔵 External and static variables are initiazlied to zero by default. Automatic variables for which there is no explicit initializer have undefined (i.e., garbage) values.
🔵 The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed. For an array, the const qualifier says that the elements will not be altered.
const double e = 2.71828182845905;
const char msg[] = "warning: ";
🔵 The const declaration can also be used with array arguments, to indicate that the function does not change that array.
int strlen(const char[]);
🔵 The binary arithmetic operators are +, -, *, / and the modulus operator %.
🔵 Integer division truncates any fractional part.
🔵
The expression x % y produces the remainder when x is divided by y, and thus
is zero when y divides x exactly.
🔵 The % operator cannot be applied to float or double.
🔵 The direction of truncation for / and the sign of the result for % are machine-dependent for negative opernds, as is the action taken on overflow or underflow. example
🔵
The binary + and - operators have the same precedence, which is lower
than the precedence of *, /, and %, which is in turn lower than
unary + and -. Arithmetic operators associate left to right.

🔵 The relational operators are
> >= < <=
they all have the same precedence. Just below them in precedence are the equality operators:
== !=
🔵
Relational operators have lower precedence than arithmetic operators, so an
expression like i < lim-1 is taken as i < (lim-1), as would be expected.
🔵 Expressions connected by logical operators && and || are evaluated left to right, and evaluation stops as soon as the truth or falsehood of the result is known. Most C programs rely on these properties.
for (i=0; i<lim-1 && (c=getchar()) != '\n' && c!= EOF; ++i)
s[i] = c;
Before reading a new character it is necessary to check that there is room to
store it in the array s, so the test i < lim-1 must be made first.
Moreover, if this test fails, we must not go on and read another character.
Similarly, it would be unfortunate if c were tested against EOF before getchar is called; therefore the call and assignment must occur before the character in c is tested.
🔵 The precedence of && is higher than that of ||, and both are lower than relational and equality operators, so expressions like above need no extra parentheses. But since the precedence of != is higher that assignment, parentheses are needed in
(c = getchar()) != '\n'
🔵 By definition, the numeric value of a relational or logical expression is 1 if the relation is true, and 0 if the relation is false. ➡ example
🔵 The unary negation operator ! converts a non-zero operand into 0, and a zero operand into 1. A common use of ! is in constructions like
if (!valid)
rather than
if (valid == 0)
🔵 When an operator has operands of different types, they are converted to a common type according to a small number of rules.
🔵
In general, the only automatic conversions are those that convert "narrower"
operand into a "wider" one without losing information, such as converting
an integer to floating point in an expression like f + i.
🔵 Expressions that don't make sense, like using a float as a subscript, are disallowed.
🔵 Expressions that might lose information, like assigning a longer integer type to a shorter, or a floating-point type to an integer, may draw a warning, but they are not illegal.
🔵 A char is just a small integer, so chars may be freely used in arithmetic expressions. This permits considerable flexibility in certain kinds of character transformations. example
🔵 In ASCII character set, corresponding upper case and lower case letters are a fixed distance apart as numeric values and each alphabet is contiguous — there is nothing but letters between A and Z, and between a and z. This latter observation is not true of the EBCDIC character set.
🔵 The standard header <ctype.h>, described in Appendix B, defines a family of functions that provide tests and conversions that are independent of character set:
isalnum() isalpha() isblank() iscntrl()
isdigit() islower() isprint() ispunct()
isspace() isxdigit() isupper() tolower()
touuper()
We will use the <ctype.h> functions from now on.
🔵 There is one subtle point about the conversion of characters to integers. The language does not specify whether variables of the type char are signed or unsigned quantities. When a char is converted to an int, can it ever produce a negative integer? The answer varies from machine to machine, reflecting differences in architecture. On some machines a char whose leftmost bit is 1 will be converted to a negative integer ("sign extension"). On others, a char is promoted to an int by adding zeros at the left end, and thus is always positive.
🔵 The definition of C guarantess that any character in the machine's standard printing character set will never be negative, so these characters will always be positive quantities in expressions. But arbitrary bit patterns stored in character variables may appear to be negative on some machines, yet positive on others. For portability, specify signed or unsigned if non-character data is to be stored in char variables.
🔵
Relational expressions like i > j and logical expressions connected by &&
and || are defined to have value 1 if true, and 0 if false.
d = c >= '0' && c <= '9'; /* d = 1 if c is a digit, and 0 if not */
🔵 Functions like isdigit may return any non-zero for true. In the test part of if, while, for, etc., "true" just means "non-zero", so this makes no difference.
🔵 In general, if an operator like + or * that takes two operands (a binary operator) has operands of different types, the "lower" type is promoted to the "higher" type before the operation proceeds. The result is of the higher type.
🔵
Section 6 of Appendix A states the conversion rules precisely. If there are no
unsigned operands, however, the following informal set of rules will
suffice:

🔵 Notice the floats in an expression are not automatically converted to double; this is a change from the original definition. In general, mathematical functions like those in <math.h> will use double precision.
🔵 The main reason for using float is to save storage in large arrays, or, less often, to save time on machines where double-precision arithmetic is particularly expensive.
🔵 Conversion rules are more complicated when unsigned operands are involved. The problem is that comparsion between signed and unsigned values are machine-dependent, beacuse they depend on the size of various integer types.
💡
Suppose that int is 16 bits and long is 32 bits. Then -1L < 1U,
beacuse 1U, which is an int, is promoted to signed long. But
-1L > 1UL, beacuse -1L is promoted to unsigned long and thus appears
to be a large positive number. ➡
test
🔵 Conversions take place across assignments; the value of the right side is converted to the type of the left, which is the type of the result.
int i;
char c;
i = c;
c = i;
the value of c is unchanged. This is true whether or not sign extension is
involved. Reversing the order of assignments might lose information,
however.x = i and i = x both
cause conversions; float to int cause truncation of any fractional part.➡ example
🔵 Since an argument of a function call is an expression, type conversion also take place when arguments are passed to functions. In the absence of a function prototype, char and short become int, and float becomes double. This is why we have declared function arguments (parameters?) to be int and double even when the function is called with char and float.
🔵
Explicit type conversions can be forced ("coerced") in any expression, with a
unary operator called a cast. In the construction (type-name) expression
the expression is converted to the named type by
the conversion rules above. ➡ example
🔵 The precise meaning of a cast is as if the expression were assigned to a variable of the specified type, which is then used in place of the whole construction. For example, the library routine sqrt expects a double argument, and will produce nonsense if inadvertently handed something else. So if n is an integer, we can use:
sqrt((double) n);
🔵 Note that the case produces the value of n in the proper type; n itself is not altered. The cast operator has the same high precedence as other unary operators.
💡 If arguments are declared by a function prototype, as they normally should be, the declaration causes automatic coercion of any arguments when the function is called. Thus, a given function prototype for sqrt:
double sqrt(double);
the call root2 = sqrt(2); coerce the integer 2 into the double value 2.0
without any need for a cast.
🔵
++ and -- may be used either as prefix operators (before the variable,
as in ++n), or postfix (after the variable: n++). In both cases, the
effect is to increment n. But the expression ++n increments n before its
value is used, while n++ increments n after its value has been used. This
means that in a context where the value is being used, not just the effect,
++n and n++ are different. if n is 5, then x = n++; sets x to 5, but
x = ++n; sets x to 6. In both cases, n becomes 6. ➡
squeeze |
strcat
if (c == '\n') {
s[i] = c;
++i;
}
/* can be replace by the more compact: */
if (c == '\n')
s[i++] = c;
🔵 The increment and decrement operators can only be applied to variables; an expression like (i+j)++ is illegal.
🔵 C provides six operators for bit manipulation; these may only be applied to integral operands, that is, char, short, int, and long whether signed of unsigned.
& bitwise AND
| bitwise inclusive OR
^ bitwise exclusive OR
<< left shift
>> right shift
~ one's complement (unary)
💡
The bitwise AND operator & is often used to mask off some set of bits;
n = n & 0177; sets to zero all but the lower-order 7 bits of n.
💡
The bitwise operator | is used to turn on bits: x = x | SET_ON; sets to
one in x the bits that are set to one in in SET_ON.
💡 The bitwise exclusive OR operator ^ sets a one in each bit position where its operands have different bits, and zero where they are the same.
🔵 The shift operators << and >> perform left and right shifts of their left operand by the number of bit positions given by the right operand, which must be positive.
🔵
x << 2 shifts the value of x left by two positions, filling vacated bits with
zero; this is equivalent to multiplication by 4.
🔵 Right shifting an unsigned quantity always fills vacated bits with zero. Right shifting a signed quantity will fill with sign bits ("arithmetic shift") on some machines and with 0-bits ("logical shift") on others.
🔵
The unary operator ~ yields the one's complement of an integer; that is, it
converts each 1-bit into a 0-bit and vice versa. For example x = x & ~077
sets the last six bits of x to zero.
🔵
Notice that x & ~077 is independent of word length, and is thus preferable to,
for example, x & 0177700, which assumes that x is a 16-bit quantity. The
portable form involves no extra cost, since ~077 is a constant
expression that can be evaluated at compile time.
➡ getbits.c (description in page 49).
🔵
Expressions such as i = i + 2 in which the variable on the left hand side is
repeated immediately on the right, can be written in the compressed form:
i += 2. The operator += is called an assignment operator.
🔵 Most binary operators (operators like + that have a left and right operand) have a corresponding assignment operator op=, where op is one of:
+ - * / % << >> & ^ |
🔵
If expr1 and expr2 are expressions, then expr1 op= expr2 is equivalent to
expr1 = (expr1) op (expr2) except that expr1 is computed only once. ➡
important example
🔵
Notice the parentheses around expr2: x *= y + 1 means x = x * (y + 1).
🔵 In bitcount.c, declaring the argument x to be unsigned ensures that when it is right-shifted, vacated bits will be filled with zeros, not sign bits, regardless of the machine the program is run on.
🔵 The assignment operators have the advantage that they correspond better to the way people think, and in many cases makes the code easier to understand. And an assignment operator may even help a compiler to produce efficient code.
🔵 We have already seen that the assignment statement has a value and can occur in expressions; the most common example is
while ((c = getchar()) != EOF)
...
The other assignment operators (+=, -=, etc.) can also occur in expressions, although this is less frequent.
In all such expressions, the type of an assignment expression is the type of its left operand, and the value is the value after the assignment.
🔵 The statements
if (a > b)
z = a;
else
z = b;
compute in z the maximum of a and b. The conditional expression, written with the ternary operator "?:", provides an alternate way to write this and similar constructions:
expr1 ? expr2 : expr3
💡 The expression expr1 is evaluated first. If it is non-zero (true), then the expression expr2 is evaluated, and that is the value of the conditional expression. Otherwise expr3 is evaluated, and that is the value. Only one of expr2 and expr3 is evaluated. Thus to set z to the maximum of a and b,
x = (a > b) ? a : b; /* z = max(a, b) */
🔵 It should be noted that the conditional expression is indeed an expression, and it can be used wherever any other expression can be.
🔵 If expr2 and expr3 are of different types, the type of the result is determined by the conversion rules discussed earlier in this chapter. For example if f is a float and n is an int, then the expression
(n > 0) ? f : n
is of type float regardless of whether n is positive.
🔵
Parentheses are not necessary around the first expression of a conditional
expression, since the precedence of ?: is very low, just above assignment.
They are advisable anyway, however, since they make the condition part of the
expression easier to see.
🔵 The conditional expression often leads to succinct code. For example, this loop prints n elements of an array, 10 per line, with each column seperated by one blank, and with each line (including the last) terminated by a newline:
for (i = 0; i < n; i++)
printf("%6d%c", a[i], (i%10==9 || i==n-1) ? '\n' : ' ');
this might look tricky, but it's more compact than the quivalent if-else. Another good example is
printf("You have %d item%s.\n", n, n == 1 ? "" : "s");
🔵
Table 2-1 summarizes the rules for precedence and associativity of all
operators, including those that we have not yet discussed. Operators on the
same line have the same precedence; rows are in order of decreasing precedence,
so, for example, *, /, and % all have the same precedence, which is
higher than that of binary + and -.

🔵 The "operator" () refers to function call. the operator -> and . are used to access members of structures; they will be covered in Chapter 6, along with sizeof (size of an object). Chapter 5 discusses * (indirection through a pointer) and & (address of an object), and Chapter 3 discusses the comma operator.
💡 Note that the precedence of the bitwise operator &, ^, and | falls below == and !=. This implies that bit-testing expression like
if ((x & MASK) == 0) ...
must be fully parenthesized to give proper results.
🔵 C, like most langugaes, does not specify the order in which the operands of an operator are evaluated. (The exceptions are &&, ||, ?:, and ','.) For example, in a statement like:
x = f() + g();
f may be evaluated before g or vice versa; thus if either f or g alters a variable on which the other depends, x can depend on the order of evaluation. Intermediate results can be stored in temporary variables to ensure a particular sequence.
❗
در عبارت
((a+b)*(c/d))-(g%h)
ترتیب ارزیابی expressionهای a تا h مشخص نمیشود.
پرانتزگذاری کامل فقط ساختار نحوی و نحوهٔ گروهبندی عبارت را مشخص میکند؛
نه ترتیب ارزیابی اجزای آن را.
برای مثال، کامپایلر میتواند ابتدا g%h را ارزیابی کند و بعد سراغ a+b برود،
یا ترتیب دیگری انتخاب کند.
اگر این expressionها اثر جانبی داشته باشند (side effects)،
باید قواعد توالی (sequencing) در C را هم در نظر بگیریم؛
در غیر این صورت ممکن است برنامه دچار رفتار تعریفنشده (undefined behavior) شود.
🔵 Similarly, the order in which function arguments are evaluated is not specified, so the statement
printf("%d %d\n", ++n, power(2, n)); /* WRONG */
can produce different results with different compilers, depending on wheter n is incremented before power is called. ➡ test
The solution, of course, is to write:
++n;
printf("%d %d\n", n, power(2, n));
🔵 Function calls, nested assignment statements, and increment and decrement operators cause "side effects" — some variable is changed as a by-product of the evaluation of an expression. In any expression involving side effects, there can be subtle dependencies on the order in which variables taking part in the expression are updated.
One unhappy situation is typified by the statement a[i] = i++;. The question
is whether the subscript is the old value of i or the new. ➡
test
🔵 The standard intentionally leaves most such matters unspecified. When side effects (assignment to variables) take place within an expression is left to the discretion of the compiler, since the best order depends strongly on machine architecture. (The standard does specify that all side effects on arguments take effects before a function is called, but that would not help in the call to printf above.)
🔔 The moral is that writing code that depends on order of evaluation is a bad programming practice in any language. Naturally, it is necessary to know what things to avoid, but if you don't know how they are done on various machines, you won't be tempted to take advantage of a particular implementation.
Excersise 2-1. Write a program to determine the ranges of char, short, int, and long variables, both signed and unsigned, by printing approporiate values from standard headers and by direct computation. Harder if you compute them: determine the ranges of the various floating-point types. □
Execrcise 2-2. Write a loop equivalent to the for loop above (page 41. section 2.6) without using && or ||. □
Execrcise 2-4. Write an alternate version of squeeze(s1, s2) that deletes each character in s1 that matches any character in the string s2. □
Execrcise 2-5. Write the function any(s1, s2), which returns the first location in the string s1 where any character from the string s2 occurs, or -1 if s1 contains no characters from s2. (The standard library function strpbrk does the same job but returns a pointer to the location.) □
Execrcise 2-6. Write a function setbits(x, p, n, y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged. □
Execrcise 2-7. Write a function invert(x, p, n) that returns x with the n bits that begin at position p inverted (i.e. 1 changed into 0 and vice versa), leaving the orders unchanged. □
Execrcise 2-8. Write a function rightrot(x, n) that returns the value of the integer x rotated to the right by n bit positions. □
Execrcise 2-9. In the two's complement number system, x &= (x-1) deletes the right most 1-bit in x. Explain why. Use this observation to write a faster version of bitcount. □
Execrcise 2-10. Rewrite the function lower, which converts upper case letters to lower case, with a conditional expression instead of if-else. □