Home  >  Article  >  Backend Development  >  In C language, legal and illegal declarations and initialization

In C language, legal and illegal declarations and initialization

王林
王林forward
2023-08-30 09:49:061398browse

In C language, legal and illegal declarations and initialization

Question

When doing C programming, mention some legal and illegal declarations and initializations?

Before discussing legal and illegal declarations and initialization, let's first look at how to declare and initialize variables in C.

Variable declaration

The following is the syntax for variable declaration -

Syntax

Datatype v1,v2,… vn;

where v1, v2,...vn are the names of variables.

For example, int sum;

float a,b;

Variables can be declared in two ways -

  • Local declaration

  • Global declaration

A "local declaration" is to declare a variable within the main block and its value is available within that block.

"Global declaration" is to declare a variable within the main block outside the main block, and its value is available throughout the program.

For example,

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

Variable initialization

The following is the syntax for variable initialization-

Syntax

Datatype v1=number;

For example,

int sum=0;
float a=1,b=4.5;

Use data types to declare variables, and we can initialize the value at declaration time. So, while initializing and declaring values, we need to follow the rules

Let us see some examples of legal and illegal declarations and initialization in C.

Example strong>

  • Char a=65;

    This is a legal statement because we can initialize variables with constants .

  • Static int p=20, q=p*p

    This is an illegal statement because static variables must be initialized with constants, but q is not initialized here

  • Double x=30 *PI

    This is a legal statement because here we initialize a variable with a constant expression.

  • Double path[]={1,PI/2, PI, 2*PI/2}

    This is a legal statement, here we initialize the array elements is a constant.

Sample program

With legal declaration and initialization

Live demonstration p>

#include<stdio.h>
void main ( ){
   int a,b;
   a= 10, b = 20;
   printf (" %d", a<b);
   printf (" %d", a<=b);
   printf (" %d", a>b);
   printf (" %d", a>=b);
   printf (" %d", a = =b);
   printf (" %d", a ! =b);
}

Output

1 1 0 0 0 1

Example

Illegal declaration and initialization-

#include <stdio.h>
int main(){
   static int p=20, q=p*p;//illegal initialization
   printf("%d%d",p,q);
   return 0;
}

Output

error will be occurred
error: initializer element is not constant
   static int p=20, q=p*p;

The above is the detailed content of In C language, legal and illegal declarations and initialization. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete