noo I can declare the global variable

2

if I want to declare these global variables

int D1=2;
int D2 = D1-2;

int main(int argc,char* argv[])
{
}

because the compiler sent me here int D2 = D1-2; ? says initializer const is not constant

    
asked by EmiliOrtega 12.02.2017 в 04:33
source

2 answers

5

You can declare it perfectly.

What you can not do is initialize it with the value of another variable.

Global variables can only be initialized with constant values. D1 = 2 is correct. D2 = D1 - 2 is incorrect , since you reference another variable.

For these cases, macros of the preprocessor are usually used:

#define VALOR_CONSTANTE 2

int D1 = VALOR_CONSTANTE;
int D2 = VALOR_CONSTANTE - 2;

The macros are not code C; your processed will perform before the compiler starts its work. Therefore, when the compiler sees the code, what it really sees is:

int D1 = 2;
int D2 = 2 - 2;

There, there is no reference to other variables, and it is compiled without problems.

EDITO

The modifier const , applicator to the declaration of variables , is used to prevent that we change the value of a variable, after initializing it:

const int a = 10;

int main( void ) {
  a = 20; // <- ERROR !!
  ...

It's a help for the developer, but a follows as a variable, not a constant value >.

const int a = 10;
int b = a - 5; // <- ERROR. a es una variable, no una expresión constante.
    
answered by 12.02.2017 / 05:46
source
2

To declare global in C and use it in the way you are showing (using constant values in your declaration) you will need the clause define , here I leave an example:

#include <stdio.h>

#define D1 5 // No requiere definir el tipo
int D2 = D1 - 2; // Requiere especificar el tipo

int main(int argc,char* argv[])
{
    printf("Valor de D2: %d\n", D2);
    return 0;
}

For this case you must use define which is a preprocessor statement, that is, its value is assigned to variable D1 as the first step when compiling the complete program, in the way you were doing before , when assigning the value of D2 the compiler would throw an error because it could not obtain the value of D1 since this was not defined at that time.

I hope I have helped you, regards!

    
answered by 12.02.2017 в 05:47