Вы находитесь на странице: 1из 4
var firstvariable - 6; var secendvarlable = 3.5, var thludVarlable ~ "I'm a string! The compiler assigns FirstVariable as type int, secondVariable as type double, and thirdvariable as type string. You don’t have to explicitly assign the type Be very clear, though: these variables are typed, and if you later ery to assign an object of the wrong type to hem you will generate a compiler error. And once the implicit eype is ser, it cannot be changed, not even explicitly. If you try to do some thing like ehis, you'll get an error ‘rstvartable ~ secondvariable; Just as if you had explicitly declared firstVariable to be of type int, once it is implicitly typed, you cannot assign the value of a variable of type double to it, because you would lose part of the value, as you'll see in Chapter 4 You may be wondering: if she compiler can determine the types of the variables for you, why not just use var all the time, instead of bothering with explcidly declaring types? A key reason is that implicit eypes make your code harder to read, and thus harder to maintain. This is more than enough reason to avoid using var except where needed. A second reason is that the compiler may guess incorrectly, and hus intro duce small but nasty errors into your code. If you were writing a math program, and you used var with your assignments like this vara = 12 var boy the compiler will decide that both @ and b should be of type int. But if you were thinking they should be of type double, and later ery something like this: ao. 355 you'l get an error, because the compiler can’t read your mind, Casting You can cause the compiler to ignore its rules of type safety and treat an object of cone type as though it were an object of another type i the types are compatible. This is called casting, Casting can be either implicit or explicie An implicit conversion happens automatically; the compiler takes care oft for you. If you have a short, and you assign it toa vanable of eype int, the compiler automat cally (and silently) casts it for you, You don't have to take any action, This is sale because an int variable can hold any value that might have been in a short variable short wyshort ~ 5; 17 other cole here. Int aylnt = myshordy 77 Amplictt cenverston a ‘Language Fundamentals Programmers often talk about this as chough the short were being tamed into an int. Whae is actually happening is that che compiler is accepting a short where it expects to find an int, because tha is a safe thing to do Implicit conversion works only when there is no possibility of loss of data, though Take a look at shis Int ayInt debe nybouble = 4.75 tyInt~ nyDoutle If you ty that assignment, the compiler gives you an error message because you can’t squeeze a decimal number into an integer space. You would lose the fractional part (7) In fact, even if you wrote: Int ayInt doable sybaite = 4 tyInt ~ nydouble the compiler would seill generate an error. Although there is no fractional pare to lose in this ease (the double is holding a whole number), the compiler can’t rake the chance that something might happen that could change the conditions, soit simply rejects all assignments of a double to an int This is where explicit conversions come in—wshen there is danger of losing data. For example, although the compiler will let you convert an int 10 a double implicily (chere’s no chance you can lose data), i will not let you implicitly convert a double to an int, as you've seen If you happen to know that its perfectly sae in your particular situation to make the assignment—if you know what you are doing—you can force the compiler to accept the assignment with an explicit east Again, some programmers talk about “casting the double into an integer,” bue you're not really changing either variable at all; you're just instructing the compiler te ignore its type-safety rules for this moment and accepe the assignment of the value held by the double variable eo the integer variable, The compiler will comply, and it will in face throw away any fractional part You specily an explicit conversion by placing the type you want to assign eo in paren- theses, immediaeely in front ofthe variable with the risky value Int mpoubte - 4.7, 17 other coe here. Int aytnt = (int) nyDoubles 17 explicht conversion ‘The keyword (int) is necessary to make the explicit conversion; without it the com: piler will generate an error. Notice, though, that in this case, you're slicing off the fractional value of the double; and myInt will have only the integral part (4), which is why we say you should know what you're doing ‘sing T 57 Sometimes you need an explicit conversion (though nor often), but ie is usually when you are taking an object out of a collection and you need to convert it to is “real” type, all of which we'll discuss in a later chapter. Even then, you rest to make sure the object you have is what you think itis. With this sort of explicit conversion, you are almost guaranteed to lose value sooner or later Constants Variables are a powerful tool, but sometimes you want to use a defined value, one whose value you want co ensure remains constant. A constant is like a variable in that ie can store a value. However, unlike a variable, you cannot change the value of a constant while the program runs. For example, you might need 10 work with the Fahrenheit freezing and boiling points of water in a program simulating a chemistry experiment. Your program wall be clearer if you name the variables that store these value: FreezingPoint and 3oilingPoint, but you do not want to permit their values to be changed while the program is executing. The solution is t0 use a constant. Constants come in three lavors: literals, symbolic constants, and enumerations Literal Constants A literal constant is just a value. For example, 32 isa literal constant. It does not have a name; itis just a literal value. And you can’t make the value 32 represent any other value. The value of 32 is always 32. You can’t assign a new value to 32, and you can’t ‘make 32 represent the value 99 no matter how hard you might try. You'll use literal constants a lot, but you probably won't chink of them as such, Symbolic Constants Symbolic constants assign a name to a constant value. You declare a symbolic con stant using the following syntax const type Adentifs value; The const keyword is followed by a type, an identifier, the assignment operator (2). and the value to assign to the constant This is similar to declaring a variable excepe that you start with the keyword const and symbolic constants must be initialized. Once initialized, a symbolic constant cannot be altered. For example, in the following declaration, 32 is a literal constant and FreezingPoint is a symbolic constant of type int: canst Int FreezingPolnt ~ 32; Example 344 illustrates the use of symbolic constants eT ‘Language Fundamentals This document was created with Win2PDF available at http:/www.win2paf.com, The unregistered version of Win2PDF is for evaluation or non-commercial use only. This page will not be added after purchasing Win2PDF.

Вам также может понравиться