C/Variables: Diferenzas entre revisións

Contido eliminado Contido engadido
Gallaecio (conversa | contribucións)
Traduzo dende en:C Programming
 
Gallaecio (conversa | contribucións)
Traduzo dende en:C Programming outro pouco
Liña 1:
{{Navegador|Manexo de erros|Entrada e saída simples}}
 
Coma a maioría das linguaxes de programación, C é quen de usar e procesar as chamadas variables e mailo seu contido. As '''variables''' son simples verbas usadas para referirse a unha localización na memoria - unha localización pode conter un valor co que esteamos a traballar.
 
Axudaría pensar nas variables coma aquelas que lle gardan un sitio a un valor. Podes pensar nunha variable como aquilo que equivale ao seu valor. Polo tanto, se tes unha variable <code>i</code> que recibe o valor <code>4</code>, entón <code>i+1</code> será equivalente a <code>5</code>.
 
Posto que C é relativamente unha linguaxe de programación de baixo nivel, antes de que un programa en C poida utilizar memoria para almacenar unha variable debe reclamar a memoria requerida para almacenar os valores desa variable. Isto faise ao '''declarar''' variables. Declarar variables é a forma que ten un programa en C para amosar o número de variables que precisa, o nome que van ter, e a cantidade de memoria que necesitarán.
<center>'''A partires deste punto o libro está a ser rescrito, ampliándose e corrixíndose os capítulos, e engadindo algúns novos.<br>Desculpe as molestias.'''</center>
 
Na linguaxe de programación C, ao manexar e traballar con variables, é importante coñecer o ''tipo'' de variables e o seu ''tamaño''. Xa que C é unha linguaxe de programación de nivel bastante baixo, estes aspectos dos seu funcionamento poden ser específicos para cada hardware, é dicir, como a linguaxe está feita para traballar nunha tipo de computadora pode ser distinta de como é para traballar noutra.
 
'''Todas''' as variables en C están suxeitas a un "tipo". Isto quere dicir que toda variable declarada deberá asignarse a un certo tipo.
 
==Declarar, inicializar e asignar variables==
No seguinte exemplo declararase un número enteiro (''integer'' en inglés), que chamaremos <code>numero_calquera</code>. Non esquezas facer fincapé no punto e coma en que remata a liña, pois así rematarán todas as declaracións.
 
'''<font style="color:#1b991b">int</font>''' numero_calquera;
{{Navegador|Manexo de erros|Entrada e saída simples}}
 
Esta declaración significa que estamos a reservar espazo para unha variable chamada <code>numero_calquera</code>, a cal será usada para almacenar datos dun número enteiro (''<code>int</code>teger'' en inglés). Nótese que temos que especificar o tipo de datos que almacenará a variable. Hai palabras clave específicas para facer isto, e verémolas a continuación.
 
Pódense declarar múltiples variables cunha soa declaración, deste xeito:
 
'''<font style="color:#1b991b">int</font>''' un_numero, outro_numero, outro_mais;
 
Tamén podemos declarar e asignarlle algún contido á variable ao mesmo tempo. Isto chámase inicialización porque é cando o se lle asigna á variable o valor inicial.
 
'''<font style="color:#1b991b">int</font>''' numero_calquera=<font style="color:#ff48ff">3</font>;
==Variables==
Like most programming languages, C is able to use and process named variables and their contents. '''Variables''' are simply names used to refer to some location in memory - a location that holds a value with which we are working.
 
En C, todas as declaracións de variables (agás as globais) deberían de facerse ao comezo dun bloque. Algúns compiladores non permiten declarar variables, engadir outras declaracións, e declarar entón máis variables. As declaracións de variables (se hai algunha) deberían de ser sempre o principio de cada bloque.
It may help to think of variables as a placeholder for a value. You can think of a variable as being equivalent to its assigned value. So, if you have a variable ''i'' that is initialized (set equal) to 4, then it follows that ''i+1'' will equal ''5''.
 
Tras declarar as variables, podes asignarlle un valor a unha variable máis adiante mediante a seguinte declaración:
Since C is a relatively low-level programming language, before a C program can utilize memory to store a variable it must claim the memory needed to store the values for a variable . This is done by '''declaring''' variables. Declaring variables is the way in which a C program shows the number of variables it needs, what they are going to be named, and how much memory they will need.
 
numero_calquera=<font style="color:#ff48ff">3</font>;
Within the C programming language, when managing and working with variables, it is important to know the ''type'' of variables and the ''size'' of these types. Since C is a fairly low-level programming language, these aspects of its working can be hardware specific - that is, how the language is made to work on one type of machine can be different from how it is made to work on another.
 
Tamén lle podes asignar a unha variable o valor doutra, deste xeito:
'''All''' variables in C are "typed". That is, every variable declared must be assigned as a certain type of variable.
 
un_numero = outro_numero;
== Declaring, Initializing, and Assigning Variables ==
Here is an example of declaring an integer, which we've called <tt>some_number</tt>. (Note the semicolon at the end of the line; that is how your compiler separates one program ''statement'' from another.)
 
Ou asígnalles a máis dunha variable o mesmo valor con esta declaración:
<source lang=c>
int some_number;
</source>
 
un_numero = outro_numero = outro_mais = <font style="color:#ff48ff">3</font>;
This statement means we're declaring some space for a variable called some_number, which will be used to store <tt>int</tt>eger data. Note that we must specify the type of data that a variable will store. There are specific keywords to do this - we'll look at them in the next section.
 
===Nomear variables===
Multiple variables can be declared with one statement, like this:
Os nomes das variables en C compóñense de letras (maiúsculas e minúsculas) e cifras. Tamén está permitida a ''barra baixa'' ('''_'''). Os nomes non poden comezar cunha cifra, e ao contrario que outras linguaxes coma [[w:Perl|Perl]] e algúns dialectos de [[w:BASIC|BASIC]]), C non fai uso de ningún prefixo especial nos nomes das variables.
<source lang=c>
int anumber, anothernumber, yetanothernumber;
</source>
We can also declare ''and'' assign some content to a variable at the same time. This is called ''initialization'' because it is the "initial" time a value has been assigned to the variable:
<source lang=c>
int some_number=3;
</source>
In C, all variable declarations (except for globals) should be done at the '''beginning''' of a block. Some compilers do not let you declare your variables, insert some other statements, and then declare more variables. Variable declarations (if there are any) should always be the '''first''' part of any block.
 
Estes son algúns exemplos de variables válidas (no referente á sintaxe, claro):
After declaring variables, you can assign a value to a variable later on using a statement like this:
<source lang=c>
some_number=3;
</source>
You can also assign a variable the value of another variable, like so:
<source lang=c>
anumber = anothernumber;
</source>
Or assign multiple variables the same value with one statement:
<source lang=c>
anumber = anothernumber = yetanothernumber = 3;
</source>
This is because the assignment ( x = y) returns the value of the assignment. x = y = z is really shorthand for x = (y = z).
 
mexanpornosetemosquedicirquechove
===Naming Variables===
Cervexa
Variable names in C are made up of letters (upper and lower case) and digits. The underscore character ("_") is also permitted. Names must not begin with a digit. Unlike some languages (such as [[w:Perl|Perl]] and some [[w:BASIC_programming_language|BASIC]] dialects), C does not use any special prefix characters on variable names.
BIC
non_si
_e_logo
_
IsoSi
 
Agora exemplos de variables que non valen:
Some examples of valid (but not very descriptive) C variable names:
<source lang=c>
foo
Bar
BAZ
foo_bar
_foo42
_
QuUx
</source>
Some examples of invalid C variable names:
<source lang=c>
2foo (must not begin with a digit)
my foo (spaces not allowed in names)
$foo ($ not allowed -- only letters, digits, and _)
while (language keywords cannot be used as names)
</source>
As the last example suggests, certain words are reserved as keywords in the language, and these cannot be used as variable names.
 
2_cervexas <font style="color:blue">// Non pode comezar cunha cifra</font>
In addition there are certain sets of names that, while not language keywords, are reserved for one reason or another. For example, a C compiler might use certain names "behind the scenes", and this might cause problems for a program that attempts to use them. Also, some names are reserved for possible future use in the C standard library. The rules for determining exactly what names are reserved (and in what contexts they are reserved) are too complicated to describe here, and as a beginner you don't need to worry about them much anyway. For now, just avoid using names that begin with an underscore character.
non si <font style="color:blue">// Non se poden usar espazos nos nomes</font>
while <font style="color:blue">// Tampouco valen as palabras clave da linguaxe C, tales coma "for", "if", "else"</font>
Quero_€_e_$ <font style="color:blue">// Carácteres coma € e $ non se poden usar, só letras, números e _</font>
E_logo? <font style="color:blue">// E dalle! "?" non é unha letra, nin un número, nin moito menos _</font>
isto_é_algo <font style="color:blue">// Non, nada de tils, así que nada de á, é, í, ó, ú</font>
pingüin_voador <font style="color:blue">// Nada de lle poñer puntiños enriba ao u</font>
ñu <font style="color:blue">// Dá a casualidade de que o ñ tampouco vale</font>
çà&#... <font style="color:blue">// En fin, ante as dúbidas, comprobade se o que escribides está no '''[[w:Alfabeto_latino#Grafemas fundamentais|alfabeto latino fundamental]]''', é unha cifra ou é '''_'''</font>
 
Como dí o terceiro exemplo, algunhas verbas están reservadas coma parabras clave na linguaxe C, polo que non se poden usar coma nomes de variable.
The naming rules for C variables also apply to other language constructs such as function names, struct tags, and macros, all of which will be covered later.
 
Ademáis, hai certas verbas que , aínda que non son palabras clave en C, están reservadas por unha ou outra razón. Pero un principiante non debería preocuparse disto, e posto que estas verbas están escritas en inglés, se utilizas o galego ou outra lingua e evitas os caracteres non válidos non deberías de ter maior problema.
== Literals ==
 
As regras para nomear variables en C aplícanse tamén a outras construccións da linguaxe tales coma nomes de funcións, etiquetas de estrutura, macros... e demáis que veremos máis adiante.
Anytime within a program in which you specify a value explicitly instead of referring to a variable or some other form of data, that value is referred to as a '''literal'''. In the initialization example above, 3 is a literal. Literals can either take a form defined by their type (more on that soon), or one can use hexadecimal (hex) notation to directly insert data into a variable regardless of its type. Hex numbers are always preceded with ''0x''. For now, though, you probably shouldn't be too concerned with hex.
 
==Literais==
== The Four Basic Types ==
 
En calqura momento nun programa no que especifiques un valor esplícito en vez de te referires a unha variable ou outro tipo de dato, ese valor considérase '''literal'''. No exemplo anterior de inicialización, <font style="color:#ff48ff">3</font> é un literal. Os literais poden tomar unha forma definida polo seu tipo (verémolo máis adiante) ou pódese usar o sistema hexadecimal (hex) para inserir directamente datos na variable sen ter en conta o seu tipo. Os números hexadecimais van sempre precedidos de ''0x''. Polo de agora, non tes por que estar interesado nos números hexadecimais, non te preocupes.
In Standard C there are four basic data types. They are <code>'''int'''</code>, <code>'''char'''</code>, <code>'''float'''</code>, and <code>'''double'''</code>.
 
==Tipos==
===The <code>int</code> type===
Na linguaxe C estándar hai catro tipos básicos de variable:
The <tt>int</tt> type stores integers in the form of "whole numbers". An integer is typically the size of one machine word, which on most modern home PCs is 32 bits (4 octets). Examples of literals are whole numbers (integers) such as 1,2,3, 10, 100... When <tt>int</tt> is 32 bits (4 octets), it can store any whole number (integer) between -2147483648 and 2147483647. A 32 bit word (number) has the possibility of representing 4294967296 numbers (2 to the power of 32).
 
===<code>int</code>===
<!-- overflows -->
As variables de tipo <code>int</code> almacenan números enteiros. O seu tamaño habitual é de 32 bits, aínda que as computadoras de 64 están a extenderse. Exemplos de literais son números enteiros coma 1, 2, 3, 6, 13, 102... Cando un <code>int</code> é de 32 bits, pode almacenar calquera número enteiro entre o -2147483648 e o 2147483647. Pero tampouco te preocupes de memorizar isto.
 
IfSe youqueres wantdeclarar tounha declare a new intnova variable, usede thetipo <ttcode>int</ttcode>, keyword.utiliza Fora examplepalabra clave <code>int</code>:
 
'''<font style="color:#1b991b">int</font>''' NumeroDePaxinas, i, l=<font style="color:#ff48ff">5</font>;
<source lang=c>
int numberOfStudents, i, j=5;
</source>
 
Nesta declaración declaramos tres variables: <code>NumeroDePaxinas</code>, <code>i</code> e <code>l</code>, séndolle a éste último asignado o literal <font style="color:#ff48ff">5</font>.
In this declaration we declare 3 variables, numberOfStudents, i and j, j here is assigned the literal 5.
 
===The <code>char</code> type===