Replacing text macros
De 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. |
El preprocesador apoya la sustitución de texto macro. Función macro-como reemplazo de texto también es apoyado .
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.
Contenido |
[editar] Sintaxis
#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] Explicación
[editar] NJ directivas
Las directivas
#define
definir la identifier como macro, que es indicar al compilador para reemplazar todas las ocurrencias sucesivas de identifier con replacement-list, que puede estar opcionalmente adicionalmente procesada. Si el identificador ya está definido como cualquier tipo de macro, el programa está mal formada . 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] Como objetos macros
Como objetos macros reemplazar todas las apariciones de identifier definido con replacement-list. Versión (1) de la Directiva
#define
se comporta exactamente igual que .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] Como función de macros
Como función de macros de reemplazar cada aparición de identifier definido con replacement-list, además de tomar una serie de argumentos, que luego reemplazar las ocurrencias correspondientes de cualquiera de los parameters en el replacement-list. El número de argumentos debe ser el mismo que el número de argumentos de macro definición (parameters) o el programa es mal formada. Si el identificador no es funcional en la notación, es decir, no tiene paréntesis después de sí misma, no se sustituye en todos .
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.
Versión (2) de la Directiva
#define
define una función simple de tipo macro .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.
Versión (3) de la Directiva
#define
define una macro de función similar con un número variable de argumentos. Los argumentos adicionales se puede acceder utilizando el identificador __VA_ARGS__
, que luego se reemplaza con argumentos, suministrados con el identificador que ser reemplazado .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.
Versión (4) de la Directiva
#define
define una macro de función similar con un número variable de argumentos, pero sin argumentos habituales. Los argumentos sólo se puede acceder con el identificador __VA_ARGS__
, que luego se reemplaza con argumentos, suministrados con identificador para ser sustituido .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 y NJ operadores
De la misma función, macros, un operador
#
antes de un identificador en el replacement-list corre el identificador a través de reemplazo de parámetros y encierra el resultado entre comillas, creando una cadena literal. Además, el preprocesador añade backslahes para escapar de las comillas rodean incrustados literales de cadena, si los hay, y dobla las barras invertidas dentro de la cadena según sea necesario. Todos los espacios en blanco iniciales y finales se retira, y cualquier secuencia de espacios en blanco en el medio del texto (pero no dentro incrustados literales de cadena) se derrumbó en un solo espacio. Esta operación se denomina "stringification". Si el resultado de stringification no es una cadena literal válido, el comportamiento no está definido .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.
Un operador
##
entre dos identificadores sucesivos en el replacement-list corre el reemplazo de parámetros en los dos identificadores y luego concatena el resultado. Esta operación se denomina "concatenación" o "token pegar". Sólo tokens que forman un símbolo válido juntos se puede pegar: identificadores que forman un identificador más largo, los dígitos que forman un número u operadores +
y =
que forman una +=
. Un comentario no puede ser creado por /
pegar y *
porque los comentarios se eliminan de texto antes de la sustitución de macros se considera. Si el resultado de la concatenación no es un token válido, el comportamiento no está definido .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
La directiva
#undef
undefines la identifier, que se cancela la anterior definición de la directiva por identifier #define
. Si el identificador no se han asociado macro, la directiva es 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 predefinidas
Los nombres de las macros siguientes están predefinidas en cualquier unidad de traducción .
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(hasta C++11) valor o 201103L(desde C++11) Original: expands to value 199711L(hasta 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) |
se expande a la 1 constante entera si la aplicación está alojada (se ejecuta en un sistema operativo), si 0 independiente (funciona sin un sistema operativo) 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__ |
expande al nombre del archivo actual, como una cadena 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__ |
amplía el número de línea del archivo fuente, una constante entera 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__ |
se expande a la fecha de la traducción, una cadena de caracteres literal de la forma "Mmm dd yyyy". El nombre del mes es como si generada 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 hasta el momento de la traducción, una cadena de caracteres literal de la 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) |
Los siguientes nombres de macro adicionales pueden estar predefinidas por las implementaciones .
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__ |
definido por la implantación valor, si está presente 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) |
definido por la implantación valor, si está presente 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) |
se expande a una constante entera de la yyyymmL forma, si wchar_t utiliza Unicode, la fecha indica que la última revisión de Unicode compatiblesOriginal: 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 si la codificación de caracteres anchos del juego de caracteres básico no puede ser igual a su codificación estrecha 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 si la aplicación tiene std::pointer_safety estricto 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) |
expande para 1 si el programa puede tener más de un hilo de ejecución 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) |
Los valores de estos macros (excepto para
__FILE__
y __LINE__
) permanecen constantes a lo largo de la unidad de traducción. Los intentos por redefinir o quitar la definición de estos macros resultado un comportamiento 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: en el ámbito de cada cuerpo de la función, hay una función especial-local variable predefinida llamada __func__(desde C++11), que se define como una matriz de caracteres estática que contiene el nombre de la función en la aplicación definida por el formato. No es una macro de preprocesador, pero se usa junto con
__FILE__
y __LINE__
, por ejemplo, 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] Ejemplo
#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 }
Output:
abcd: 12 fff: 2 kkk: 23 34 million