C/Variables: Diferenzas entre revisións

Contido eliminado Contido engadido
Gallaecio (conversa | contribucións)
Gallaecio (conversa | contribucións)
Liña 158:
Teña en conta que un compilador que siga a normativa estándar debería amosar unha alerta avisando do intento de cambiar o valor dunha variable <tt>const</tt>, mais despois de facelo o compilador é libre de ignorar o cualificador <tt>const</tt>.
 
==Número máxicos==
== Magic numbers ==
Ao escribir programas en C, pode que che dé por escribir código que dependera de certos números. Por exemplo, poderías estar a escribir un programa para uns almacéns de comestibles. Este programa ten milleiros e milleiros de liñas de código. O programador decide representar o importe dunha lata de mexillóns, actualmente 71 céntimos, como un literal en todo o código. Agora imaxina que coa crise isto aumenta a 701 céntimos. O programador tería entón que cambiar manualmente as entradas de 71 polas de 701. Ben pensado, isto tampouco é un gran problema. Para algo temos o "Buscar e substituír todos". Pois ben, agora pensa que unha lata de sardiñas custa tamén 71 céntimos. Vas bo, rapaz, vaia choio que vas levar para comprobar a man cando é un e cando outro e substituír o que corresponda.
When you write C programs, you may be tempted to write code that will depend on certain numbers. For example, you may be writing a program for a grocery store. This complex program has thousands upon thousands of lines of code. The programmer decides to represent the cost of a can of corn, currently 99 cents, as a literal throughout the code. Now, assume the cost of a can of corn changes to 89 cents. The programmer must now go in and manually change each entry of 99 cents to 89. While this is not that big of a problem, considering the "global find-replace" function of many text editors, consider another problem: the cost of a can of green beans is also initially 99 cents. To reliably change the price, you have to look at every occurrence of the number 99.
 
C posúe certa funcionalidade para evitar isto. As formas para facelo son case equivalentes, pero nalgúns casos será preferible usar un método concreto en detrimento doutro.
C possesses certain functionality to avoid this. This functionality is approximately equivalent, though one method can be useful in one circumstance, over another.
 
=== Using the <tt>const</tt> keyword ===
TheA palabra clave <tt>const</tt> keywordaxuda helpsa eliminar eradicateos '''magicnúmeros numbersmáxicos'''. ByAo declaringdeclarar aunha variable <tt>const cornlatamexillons_marcax</tt> atao theprincipio beginningdun ofbloque, aun block,programador pode limitarse a programmercambiar canesa simplyvariable changeconstante, thate constnon se preocupar de establecer ando notseu havevalor toen worrytodos aboutos settinglugares theonde valuesexa elsewherepreciso.
 
ThereTamén istemos alsooutro anotherxeito methodde forevitar avoidingos magicnúmeros numbersmáxicos. ItÉ ismoito much moremáis flexible thanque o <tt>const</tt>, ande alsotamén muchmáis moreproblemático problematicen inmoitos many waysaspectos. ItAdemais alsoen involveslugar thede preprocessor,implicar asao opposedcompilador, toimplica theao compiler. Behold..preprocesador.
 
=== <tt>#define</tt> ===
Ao escribir prorgamas, podes crear o que se coñece coma un ''macro'', de xeito que ao ler a computadora o teu código, substituirá todas as instancias dunha verba pola expresión especificada. Velaquí un exemplo:
When you write programs, you can create what is known as a ''macro'', so when the computer is reading your code, it will replace all instances of a word with the specified expression.
 
<code><font style="color:#bc5ff8">#define</font> <font style="color:#ff48ff">custo_dos_mexillons</font>
Here's an example. If you write
<source lang=c>
#define PRICE_OF_CORN 0.99
</source>
when you want to, for example, print the price of corn, you use the word <code>PRICE_OF_CORN</code> instead of the number 0.99 - the preprocessor will replace all instances of <code>PRICE_OF_CORN</code> with 0.99, which the compiler will interpret as the literal <code>double</code> 0.99. The preprocessor performs substitution, that is, <code>PRICE_OF_CORN</code> is replaced by 0.99 so this means there is no need for a semicolon.
 
Isto serviría para se, por exemplo, para facer referencia ao custo dos mexillóns pos <tt>custo_dos_mexillons</tt> en lugar de <tt>0.71</tt> (recorda que en inglés usan o punto ('''.''') para separar os decimais), de xeito que o precompilador buscará todos os <tt>custo_dos_mexillons</tt> para substituílos polo literal de tipo double <tt>0.71</tt>.
It is important to note that <code>#define</code> has basically the same functionality as the "find-and-replace" function in a lot of text editors/word processors.
 
Hai que facer especial fincapé en que a funcionalidade do <tt>#define</tt> é a mesma que a do "Buscar e substituír" dos editores de texto. Para algunhas cousas, o <tt>#define</tt> pode ser nocivo, e por regra xeral é preferible usar o <tt>const</tt> se o <tt>#define</tt> non é imprescindible. Así mesmo, é aconsellable escribir as palabras <tt>#define</tt> en maiúsculas, para indicarlle ao resto dos programadores que se trata dun macro.
For some purposes, <code>#define</code> can be harmfully used, and it is usually preferable to use <code>const</code> if <code>#define</code> is unnecessary. It is possible, for instance, to <code>#define</code>, say, a macro <code>DOG</code> as the number 3, but if you try to print the macro, thinking that <code>DOG</code> represents a string that you can show on the screen, the program will have an error. <code>#define</code> also has no regard for type. It disregards the structure of your program, replacing the text ''everywhere'' (in effect, disregarding scope), which could be advantageous in some circumstances, but can be the source of problematic bugs.
 
You will see further instances of the <code>#define</code> directive later in the text. It is good convention to write <code>#define</code>d words in all capitals, so a programmer will know that this is not a variable that you have declared but a <code>#define</code>d macro.
 
<!-- Mention enum for constant defining! -->
 
== Scope ==