C Tutorial/Language/Variable Declaration

Материал из C\C++ эксперт
Версия от 10:32, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Define three variables and use assignment operator to assign value

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);
    }

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.


int answer;     /* the result of our expression */
  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

#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;
}
Average of the ten numbers entered is: 48.000000

Meaningful variable name

int p,q,r;

Use printf to output variable

#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);
    }
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

#include <stdio.h>
int main(void)
{
  int salary;            
  salary = 10000;        
  printf("My salary is %d.", salary);
  return 0;
}
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:


average            /* average of all grades */ 
    pi                 /* pi to 6 decimal places */    
    number_of_students /* number students in this class */