The Complete Rust Programming Reference Guide by Rahul Sharma

The Complete Rust Programming Reference Guide by Rahul Sharma

Author:Rahul Sharma
Language: eng
Format: epub
Tags: COM051000 - COMPUTERS / Programming / General, COM051230 - COMPUTERS / Software Development and Engineering / General, COM051300 - COMPUTERS / Programming / Algorithms
Publisher: Packt Publishing
Published: 2019-05-20T11:39:31+00:00


#include <stdio.h>

#define SWITCH(a, b) { temp = b; b = a; a = temp; }

int main() {

int x=1;

int y=2;

int temp = 3;

SWITCH(x, y);

printf("x is now %d. y is now %d. temp is now %d\n", x, y, temp);

}

Compiling this with gcc c_macros.c -o macro && ./macro gives the following output:

x is now 2. y is now 1. temp is now 2

In the preceding code, unless we declare our own temp variable inside the SWITCH macro, the original temp variable in main is modified by the expansion of the SWITCH macro. This unhygienic nature makes C macros unsound and brittle, and can easily make a mess unless special precautions are taken, such as using a different name for the temp variable within the macro.

Rust macros on the other hand are hygienic and also more context aware than just performing simple string substitution and expansion. They are aware of the scope of the variables that have been referenced within the macro and do not shadow any identifiers that have already been declared outside. Consider the following Rust program, which tries to implement the macro we used previously:

// c_macros_rust.rs



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.