Replacing text macros
Da cppreference.com
< cpp | preprocessor
![]() |
This page has been machine-translated from the English version of the wiki using Google Translate.
The translation may contain errors and awkward wording. Hover over text to see the original version. You can help to fix errors and improve the translation. For instructions click here. |
O pré-processador suporta substituição macro texto. -Função como substituto macro de texto também é suportado.
Original:
The preprocessor supports text macro replacement. Function-like text macro replacement is also supported.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Índice |
[editar] Sintaxe
#define identifier replacement-list
|
(1) | ||||||||
#define identifier( parameters ) replacement-list
|
(2) | ||||||||
#define identifier( parameters, ... ) replacement-list
|
(3) | ||||||||
#define identifier( ... ) replacement-list
|
(4) | ||||||||
#undef identifier
|
(5) | ||||||||
[editar] Explicação
[editar] NJ directivas
As directivas
#define
definir o identifier como macro, que é instruir o compilador para substituir todas as ocorrências sucessivas de identifier com replacement-list, que pode ser opcionalmente adicionalmente processado. Se o identificador já está definida como qualquer tipo de macro, o programa é mal-formado. Original:
The
#define
directives define the identifier as macro, that is instruct the compiler to replace all successive occurrences of identifier with replacement-list, which can be optionally additionally processed. If the identifier is already defined as any type of macro, the program is ill-formed. The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[editar] Objeto como macros
Objeto como macros substituir cada ocorrência de identifier definido com replacement-list. Versão (1) da directiva
#define
se comporta exatamente assim.Original:
Object-like macros replace every occurrence of defined identifier with replacement-list. Version (1) of the
#define
directive behaves exactly like that.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[editar] -Função como macros
-Função como macros substituir cada ocorrência de identifier definido com replacement-list, além de tomar uma série de argumentos, que, em seguida, substituir ocorrências correspondentes de qualquer dos parameters no replacement-list. O número de argumentos deve ser o mesmo que o número de argumentos a definição de macros (parameters) ou o programa é mal formado. Se o identificador não está na notação-funcional, isto é, não tem parênteses após si só, não é substituído de todo.
Original:
Function-like macros replace each occurrence of defined identifier with replacement-list, additionally taking a number of arguments, which then replace corresponding occurrences of any of the parameters in the replacement-list. The number of arguments must be the same as the number of arguments in macro definition (parameters) or the program is ill-formed. If the identifier is not in functional-notation, i.e. does not have parentheses after itself, it is not replaced at all.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Versão (2) da directiva
#define
define uma macro-função como simples.Original:
Version (2) of the
#define
directive defines a simple function-like macro.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Versão (3) da directiva
#define
define uma macro-função como com número variável de argumentos. Os argumentos adicionais pode ser acedida utilizando __VA_ARGS__
identificador, o qual é, então, substituído com argumentos, fornecidos com o identificador de ser substituídos.Original:
Version (3) of the
#define
directive defines a function-like macro with variable number of arguments. The additional arguments can be accessed using __VA_ARGS__
identifier, which is then replaced with arguments, supplied with the identifier to be replaced.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Versão (4) da directiva
#define
define uma macro-função como com número variável de argumentos, mas sem argumentos regulares. Os argumentos pode ser acedida apenas com __VA_ARGS__
identificador, o qual é, então, substituído com argumentos, fornecidos com identificador de ser substituídos.Original:
Version (4) of the
#define
directive defines a function-like macro with variable number of arguments, but no regular arguments. The arguments can be accessed only with __VA_ARGS__
identifier, which is then replaced with arguments, supplied with identifier to be replaced.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[editar] NJ e NJ operadores
Em função de como macros, um operador de
#
antes de um identificador na replacement-list corre o identificador através de substituição de parâmetro e encerra o resultado entre aspas, efetivamente criando uma seqüência literal. Além disso, o pré-processador acrescenta backslahes para escapar das aspas literais de cadeia embutidos, se houver, e dobra as barras invertidas dentro da cadeia, se necessário. Todos esquerda e à direita espaço em branco é removida, e qualquer seqüência de espaços em branco no meio do texto (mas não literais de cadeia no interior embutidos) é recolhido em um único espaço. Esta operação é denominada "stringification". Se o resultado da stringification não é uma seqüência válida literal, o comportamento é indefinido.Original:
In function-like macros, a
#
operator before an identifier in the replacement-list runs the identifier through parameter replacement and encloses the result in quotes, effectively creating a string literal. In addition, the preprocessor adds backslahes to escape the quotes surrounding embedded string literals, if any, and doubles the backslashes within the string as necessary. All leading and trailing whitespace is removed, and any sequence of whitespace in the middle of the text (but not inside embedded string literals) is collapsed to a single space. This operation is called "stringification". If the result of stringification is not a valid string literal, the behavior is undefined.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Um operador de
##
entre dois identificadores sucessivas no replacement-list executado a substituição de parâmetro sobre os dois identificadores e então concatena o resultado. Esta operação é chamada de "concatenação" ou "token colando". Apenas fichas que formam um token válido em conjunto pode ser colado: identificadores que formam um longo identificador, dígitos que formam um número ou operadores +
e =
que formam uma +=
. Um comentário não pode ser criado por /
colar e *
porque os comentários são removidos do texto antes de substituição de macro é considerado. Se o resultado da concatenação não é um token válido, o comportamento é indefinido.Original:
A
##
operator between any two successive identifiers in the replacement-list runs parameter replacement on the two identifiers and then concatenates the result. This operation is called "concatenation" or "token pasting". Only tokens that form a valid token together may be pasted: identifiers that form a longer identifier, digits that form a number, or operators +
and =
that form a +=
. A comment cannot be created by pasting /
and *
because comments are removed from text before macro substitution is considered. If the result of concatenation is not a valid token, the behavior is undefined.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[editar] NJ directiva
A directiva
#undef
undefines o identifier, que é cancela definição prévia do identifier pela directiva #define
. Se o identificador não têm associado a macro, a directiva é ignorada.Original:
The
#undef
directive undefines the identifier, that is cancels previous definition of the identifier by #define
directive. If the identifier does not have associated macro, the directive is ignored.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[editar] Macros pré-definidas
Os nomes de macro a seguir são predefinidos em qualquer unidade de tradução.
Original:
The following macro names are predefined in any translation unit.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
__cplusplus |
se expande para 199711L(até C++11) valor ou 201103L(desde C++11) Original: expands to value 199711L(até C++11) or 201103L(desde C++11) The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (macro constante) |
__STDC_HOSTED__ (C++11) |
expande para o 1 constante inteira, se a execução está hospedado (executado em um sistema operacional), 0 se independente (funciona sem um sistema operacional) Original: expands to the integer constant 1 if the implementation is hosted (runs under an OS), 0 if freestanding (runs without an OS) The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (macro constante) |
__FILE__ |
se expande para o nome do arquivo atual, como uma cadeia de caracteres literal Original: expands to the name of the current file, as a character string literal The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (macro constante) |
__LINE__ |
se expande para o número da linha fonte do arquivo, uma constante inteira Original: expands to the source file line number, an integer constant The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (macro constante) |
__DATE__ |
expande-se para a data da tradução, uma cadeia de caracteres literal da forma "Mmm dd aaaa". O nome do mês é como se gerado por std::asctime() Original: expands to the date of translation, a character string literal of the form "Mmm dd yyyy". The name of the month is as if generated by std::asctime() The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (macro constante) |
__TIME__ |
expande-se para o tempo de tradução, uma cadeia de caracteres literal da forma "hh: mm: ss" Original: expands to the time of translation, a character string literal of the form "hh:mm:ss" The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (macro constante) |
Os seguintes nomes de macro adicionais podem ser predefinidos pelas implementações.
Original:
The following additional macro names may be predefined by the implementations.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
__STDC__ |
implementação valor definido, se houver Original: implementation-defined value, if present The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (macro constante) |
__STDC_VERSION__ (C++11) |
implementação valor definido, se houver Original: implementation-defined value, if present The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (macro constante) |
__STDC_ISO_10646__ (C++11) |
expande a uma constante inteira do yyyymmL forma, se wchar_t usa Unicode, a data indica a última revisão do Unicode suportadoOriginal: expands to an integer constant of the form yyyymmL , if wchar_t uses Unicode, the date indicates the latest revision of Unicode supportedThe text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (macro constante) |
__STDC_MB_MIGHT_NEQ_WC__ (C++11) |
se expande para 1 se codificação de caracteres de largura do conjunto básico de caracteres não pode ser igual a sua codificação estreito Original: expands to 1 if wide character encoding of the basic character set may not equal their narrow encoding The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (macro constante) |
__STDCPP_STRICT_POINTER_SAFETY__ (C++11) |
se expande para 1 se a implementação tem std::pointer_safety estrito Original: expands to 1 if the implementation has strict std::pointer_safety The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (macro constante) |
__STDCPP_THREADS__ (C++11) |
se expande para 1 se o programa pode ter mais de uma thread de execução Original: expands to 1 if the program can have more than one thread of execution The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (macro constante) |
Os valores destas macros (excepto para
__FILE__
e __LINE__
) permanecem constantes em toda a unidade de tradução. Tentativas de redefinir ou indefinir estes resultado macros em um comportamento indefinido.Original:
The values of these macros (except for
__FILE__
and __LINE__
) remain constant throughout the translation unit. Attempts to redefine or undefine these macros result in undefined behavior.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Nota: no âmbito de cada corpo da função, existe uma função de variável local especial predefinido chamado __func__(desde C++11), definido como uma matriz de caracteres estático com o nome da aplicação, em função do formato definido. Não é uma macro de pré-processamento, mas é usada em conjunto com
__FILE__
e __LINE__
, eg por assert.Original:
Note: in the scope of every function body, there is a special function-local predefined variable named __func__(desde C++11), defined as a static character array holding the name of the function in implementation-defined format. It is not a preprocessor macro, but it is used together with
__FILE__
and __LINE__
, e.g. by assert.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[editar] Exemplo
#include <iostream> //make function factory and use it #define FUNCTION(name, a) int fun_##name() { return a;} FUNCTION(abcd, 12); FUNCTION(fff, 2); FUNCTION(kkk, 23); #undef FUNCTION #define FUNCTION 34 #define OUTPUT(a) std::cout << #a << '\n' int main() { std::cout << "abcd: " << fun_abcd() << '\n'; std::cout << "fff: " << fun_fff() << '\n'; std::cout << "kkk: " << fun_kkk() << '\n'; std::cout << FUNCTION << '\n'; OUTPUT(million); //note the lack of quotes }
Saída:
abcd: 12 fff: 2 kkk: 23 34 million