Going over C, I was wondering:
What is the difference between macros and consts, if in general the purpose of each one is to create a value that never changes?
Example of using a const:
#include <stdio.h>
void main()
{
const int height = 100; /*constante de tipo entera*/
const float number = 3.14; /*constante de tipo real*/
const char letter = 'A'; /*constante de tipo caracter*/
const char letter_sequence[10] = "ABC"; /*constante de tipo cadena*/
const char backslash_char = '\?'; /*contante de caracter especial*/
printf("Valor de la altura :%d \n", height );
printf("valor del número : %f \n", number );
printf("valor de la letra : %c \n", letter );
printf("Valor de la secuencia de letras : %s \n", letter_sequence);
printf("Valor del caracter de barra invertida : %c \n", backslash_char);
}
Example of the use of macros:
#include<stdio.h>
#define PI 3.1416//Macro
int main(){
int x = 10:
suma = PI + x;
printf("la suma es %.2f",suma);
return 0;
}
Macros are directives handled by the preprocessor... a macro ends up generating legal C code, which is what the compiler will ultimately receive.
That is, for the following example:
The compiler would get the following:
On the other hand, constants are
variableelements that cannot see their value modified. That is, for the following example:The compiler will have to pass the value of
constante
to the functionprintf
. The two calls could only be similar if the compiler introduces some optimization that allows to eliminate this intermediate step.