Preprocessor, const, static, and enum · Pré-processador, const, static e enum
What runs before the compiler
- Before the compiler sees your code, the preprocessor handles every line that starts with
#. - It pastes in headers, replaces macros, and removes comments — a simple text step.
- You have used it already:
#include <stdio.h>is a preprocessor command.
O que acontece antes do compilador
- Antes que o compilador veja seu código, o preprocessador lida com toda linha que começa com
#. - Ele cola headers, substitui macros e remove comentários — um passo simples de texto.
- Você já usou isso:
#include <stdio.h>é um comando do preprocessador.
#include and #define
#include <stdio.h>pastes the contents of a header so you can use its functions.#define PI 3.14159makesPIa macro: the preprocessor replaces everyPIwith that text.- Macros have no type and no semicolon — they are pure text replacement.
#include e #define
#include <stdio.h>cola o conteúdo de um header para que você possa usar suas funções.#define PI 3.14159transformaPIem um macro: o preprocessador substitui todoPIpor esse texto.- Macros não têm tipo nem ponto e vírgula — são substituição pura de texto.
const vs #define
const double pi = 3.14159;is a real variable that cannot be changed. It has a type, so the compiler checks it.#define PI 3.14159is just text replacement, done before compiling.- Modern C usually prefers
constfor values, but#defineis still common for constants and flags.
const vs #define
const double pi = 3.14159;é uma variável real que não pode ser alterada. Ela tem um tipo, então o compilador verifica.#define PI 3.14159é apenas substituição de texto, feita antes de compilar.- C moderno geralmente prefere
constpara valores, mas#defineainda é comum para constantes e flags.
static and enum
- A
staticvariable inside a function keeps its value between calls — it is set up once, not reset every time the function runs. - An
enumgives names to a set of relatedintvalues:enum Suit { HEARTS, DIAMONDS, CLUBS, SPADES };(hereHEARTSis0). - Both make code clearer:
staticfor memory that persists,enumfor named choices.
static e enum
- Uma variável
staticdentro de uma função mantém seu valor entre chamadas — ela é configurada uma vez, não resetada toda vez que a função roda. - Um
enumdá nomes a um conjunto de valoresintrelacionados:enum Suit { HEARTS, DIAMONDS, CLUBS, SPADES };(aquiHEARTSé0). - Ambos tornam o código mais claro:
staticpara memória que persiste,enumpara escolhas nomeadas.
#include <stdio.h>
#define GREETING "Hello"
enum Color { RED, GREEN, BLUE };
int main(void) {
printf("%s\n", GREETING); // Hello
enum Color c = GREEN;
printf("%d\n", c); // 1
return 0;
}
Common mistakes
#definedoes plain text replacement — wrap macro bodies in parentheses.constcannot change; astaticlocal keeps its value between calls.
Erros comuns
#definefaz substituição de texto simples — envolva corpos de macro em parênteses.constnão pode mudar; uma variável localstaticmantém seu valor entre chamadas.
Now you try
- Use the given
#defineandenumin the starters. - A
staticlocal variable remembers its value across calls. Do not write amain— the checker provides one.
Agora você tenta
- Use os
#defineeenumfornecidos nos starters. - Uma variável local
staticlembra seu valor entre chamadas. Não escreva ummain— o checker fornece um.
The · A enum Suit { HEARTS, DIAMONDS, CLUBS, SPADES } is given. Complete const char *suit_name(enum Suit s) so it returns the name ("Hearts", "Diamonds", "Clubs", "Spades") using a switch. Do not · não write a main. · O enum Suit { HEARTS, DIAMONDS, CLUBS, SPADES } é fornecido. Complete const char *suit_name(enum Suit s) para retornar o nome ("Hearts", "Diamonds", "Clubs", "Spades") usando um switch. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
A macro #define PI 3.14159265358979 is given. Complete double circle_area(double r) so it returns the area of a circle, PI * r * r, using the macro. Do not · não write a main. · Uma macro #define PI 3.14159265358979 é fornecida. Complete double circle_area(double r) para que retorne a área de um círculo, PI * r * r, usando a macro. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete int next_id(void) using a static local counter, so the first call returns 1, the next 2, then 3, and so on. Do not · não write a main. · Complete int next_id(void) usando um contador local static, para que a primeira chamada retorne 1, a próxima 2, depois 3, e assim por diante. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.