{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

115_pdfsam_cs2022

115_pdfsam_cs2022 - #define sum_sq(a b a*a b*b int main...

This preview shows pages 1–6. Sign up to view the full content.

Macros with arguments You can #define macros with parameters Looks like a function call, but it isn’t Like functions, macros make code easier to read But don’t have the overhead associated with function calls Compare: #define sum_sq(a,b) a*a + b*b int main() { double num1 = 3.0, ssq; ssq = sum_sq(num1, 5.0); return 0; } double sum_sq(double a, double b){ return a*a + b*b; } int main() { double num1 = 3.0, ssq; ssq = sum_sq(num1, 5.0); return 0; } Macro Function

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Macros with arguments Preprocessor literally does a search-and- replace operation before the code is compiled #include <stdio.h> #define sum_sq(a, b) a*a + b*b int main() { double num1 = 3.0, ssq; ssq = sum_sq(num1, 5.0); return 0; } /* ..Contents of stdio.h.. */ int main() { double num1 = 3.0, ssq; ssq = num1*num1 + 5.0*5.0; return 0; } Before Processing After Processing
Macro pitfalls “Search-and-replace” can be problematic It’s easy to write macros that have unintended consequences #include <stdio.h>

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: #define sum_sq(a, b) a*a + b*b int main() { double num1 = 3.0, ssq; ssq = sum_sq(num+3, 5.0); return 0; } /* . .Contents of stdio.h. . */ Before Processing After Processing Macro pitfalls “Search-and-replace” can be problematic It’s easy to write macros that have unintended consequences #include <stdio.h> #define sum_sq(a,b) (a)*(a) + (b)*(b) int main() { double num1 = 3.0, ssq; ssq = sum_sq(num+3, 5.0); return 0; } ssq = (num+3)*(num+3)+(5.0)*(5.0); Before Processing After Processing Macro pitfalls “Search-and-replace” can be problematic It’s easy to write macros that have unintended consequences #include <stdio.h> #define sum_sq(a,b) (a)*(a) + (b)*(b) int main() { double num1 = 3.0, ssq; ssq = sum_sq( rand() , 5.0); return 0; } Before Processing After Processing More preprocessor features The preprocessor has many other features check K&R for details...
View Full Document

{[ snackBarMessage ]}

Page1 / 6

115_pdfsam_cs2022 - #define sum_sq(a b a*a b*b int main...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online