C Tutorial/Language/Variable Declaration

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Define three variables and use assignment operator to assign value

<source lang="cpp">int main()

   {  
       int term;       /* term used in two expressions */ 
       int term_2;     /* twice term */   
       int term_3;     /* three times term */ 
       term = 3 * 5;  
       term_2 = 2 * term; 
       term_3 = 3 * term; 
       return (0);
   }</source>

How to declare a variable

A variable declaration serves three purposes:

  1. It defines the name of the variable.
  2. It defines the type of the variable (integer, real, character, etc.).
  3. It gives the programmer a description of the variable.


<source lang="cpp">int answer; /* the result of our expression */</source>

  1. The keyword int tells C that this variable contains an integer value.
  2. The variable name is answer.
  3. The semicolon (;) marks the end of the statement.
  4. The comment is used to define this variable for the programmer.

Initialize int value in declaration

<source lang="cpp">#include <stdio.h> int main(void) {

 int number0 = 10, number1 = 40, number2 = 50, number3 = 80, number4 = 10;
 int number5 = 20, number6 = 30, number7 = 60, number8 = 70, number9 = 110;
 int sum = number0 + number1+ number2 + number3 + number4+
       number5 + number6 + number7 + number8 + number9;
 float average = (float)sum/10.0f;
 printf("\nAverage of the ten numbers entered is: %f\n", average);
 return 0;

}</source>

Average of the ten numbers entered is: 48.000000

Meaningful variable name

<source lang="cpp">int p,q,r;</source>

Use printf to output variable

<source lang="cpp">#include <stdio.h>

   int main() 
   {  
       int term;       /* term used in two expressions */ 
       term = 3 * 5;  
       printf("Twice %d is %d\n", term, 2*term);  
       printf("Three times %d is %d\n", term, 3*term);
       return (0);
   }</source>
Twice 15 is 30
Three times 15 is 45

The number of %d conversions should match the number of expressions.

Using a variable to store value

<source lang="cpp">#include <stdio.h> int main(void) {

 int salary;            
 salary = 10000;        
 printf("My salary is %d.", salary);
 return 0;

}</source>

My salary is 10000.

Variables

  1. You can store values in variables.
  2. Each variable is identified by a variable name.
  3. Each variable has a variable type.
  4. Variable names start with a letter or underscore (_), followed by any number of letters, digits, or underscores.
  5. Uppercase is different from lowercase, so the names sam, Sam, and SAM specify three different variables.
  6. The variables are defined at the begining of the block.

The following is an example of some variable names:


<source lang="cpp">average /* average of all grades */

   pi                 /* pi to 6 decimal places */    
   number_of_students /* number students in this class */</source>