70 likes | 84 Vues
Learn the careful rules and best practices for handling type conversions in ANSI-C to reduce errors and improve code quality. Understand automatic and explicit type conversions, exceptions, and formatted numbers for output.
E N D
Conversions of the type of the value of an expression ANSI-C
Careful rules to follow • You should know the type of the resulting expression • You should match the type of the resulting expression with the expected type of • The variable being assigned • The parameter being matched by the expression as argument • The type of the result of the function • Knowing that you matching or did not match it EXPLICITELY will reduce your errors.
Autmatic type conversions for matching • If the type of the value of the expression does not match the type expected (by the variable, by the parameter, by the function return type) the C language will convert the type of the resulting value to the expected type. • This implicitely, automatic match performed by the language can produce be the source of hidden errors in your code.
Type of an expression • When all the operands of an operation are of the same type, the resulting value will be of that type. • We can write in C expressions where the operands are of different types. How to compute it’s the type of the resulting value? Based on the type of the dominand operand • long double • double • float • unsigned • int
Exceptions • For any expression involving only char, signed or unsigned char, short, or unsigned short, dominating type will be int or unsigned. • For any expression involving only long int and unsigned int, dominating type is implementation dependent; should be unsigned long int, or long int.
Explicit conversions: Casting • The language will implicitely find the type of the value of a resulting expression (important when the expression has mixed type operands). • Sometimes programmer knows the type that the resulting value ought to have, and it can direct the machine to compute it: • (type) expression • Example: int x; int y; • x/y or (float) x / y • Important: the precedence of (cast) : lower than any unary operator but hiegher than any binary operator.
Formatted numbers for output: • As you know you can specify the format for output values • %d • %c • %s • %f • %e • These can include a specification for field width: • %10d • %14.5f