首页 > 文章列表 > 解释变量声明和C语言中变量的规则

解释变量声明和C语言中变量的规则

关键词:变量声明C语言变量规则
238 2023-08-31

首先让我们了解一下什么是变量。

变量

  • 它是用来存储数据值的内存位置的名称。

  • 变量在执行过程中可以在不同的时间点取不同的值。

  • 程序员可以选择有意义的变量名称,以反映其在程序中的功能或性质。

例如,sum(总和),avg(平均值),total(总计)等。

变量命名规则

变量命名的规则如下所示:

  • 变量名必须以字母开头。

  • 在ANSI标准中,变量的最大长度为31个字符。但是,许多编译器只考虑前八个字符。

  • 大小写字母是不同的。例如:total、TOTAL、Total是3个不同的变量。

  • 变量名不能是关键字。

  • 不允许使用空格。

变量声明

下面是变量声明的语法和示例:

语法

变量声明的语法如下所示:

Datatype v1,v2,… vn;

Where, v1, v2,...vn are names of variables.

For example,

int sum;
float a,b;

变量可以通过两种方式进行声明 −

  • 局部声明 − ‘局部声明’ 是在主代码块内部声明变量,其值只在该代码块内有效。

  • 全局声明 − ‘全局声明’ 是在主代码块外部声明变量,其值在整个程序中都有效。

示例

以下是C语言中局部和全局变量声明的示例程序 −

int a, b; /* global declaration*/
main ( ){
   int c; /* local declaration*/
   - - -
}

示例

以下是一个用于查找商品的售价(SP)和成本价(CP)的C程序 −

 在线演示

#include<stdio.h>
int main(){
   float CostPrice, SellingPrice, Amount; //variable declaration
   //costprice & sellingprice are variables and
   //float is a datatype
   printf("

product cost price: ");    scanf("%f", &CostPrice);    printf("

product selling price : ");    scanf("%f", &SellingPrice);    if (SellingPrice > CostPrice){       Amount = SellingPrice - CostPrice;       printf("

Profit Amount = %.4f", Amount);    }    else if(CostPrice > SellingPrice){       Amount = CostPrice - SellingPrice;       printf("

Loss Amount = %.4f", Amount);    }    else       printf("

No Profit No Loss!");    return 0; }

输出

输出如下 −

product cost price : 240
product selling price : 280
Profit Amount = 40.0000