C Language: Macros inside the parameters are error-prone, when used as far as possible parentheses and examples

Source: Internet
Author: User

Macros inside parameters without parentheses error-prone, when used as far as possible parentheses

Program 1:

#include <stdio.h>

#define sqare(X) x*x

int Main ()

{

int n = ten;

int m= Sqare (n);

printf ("m=%d\n", m);

return 0;

}

Results:

m=100

Please press any key to continue ...

Analysis: There seems to be no problem, see the following two examples

Program 2:

#include <stdio.h>

#define sqare(X) x*x

int Main ()

{

int m = Sqare (1 + 3); //1+3*1+3=7

printf ("m=%d\n", m);

return 0;

}

Results:

M=7

Please press any key to continue ...

Corrective Procedure 2:

#include <stdio.h>

#define sqare(x) (x)* (x )

int Main ()

{

intm =Sqare(1+3);//(1+3)*(1+3)= -

printf ("m=%d\n", m);

return 0;

}

Results:

M=16

Please press any key to continue ...

Program 3:

#include <stdio.h>

#define ADD(X) x+x //No parentheses error-prone

int Main ()

{

int m = 10* ADD (2); //10*2+2

printf ("m=%d\n", m);

return 0;

}

Results:

M=22

Please press any key to continue ...

Corrective Procedure 3:

#include <stdio.h>

#define ADD(X) (x+x)

int Main ()

{

int Span style= "font-family: ' The new song Body '; Font-size:13px;background:rgb (255,255,255);" > m = 10* add (2); //10* Span style= "font-family: ' New song body '; Color:rgb (0,128,0); Font-size:13px;background:rgb (255,255,255);" > ( 2+2 )

printf ("m=%d\n", m);

return 0;

}

Results:

M=40

Please press any key to continue ...


This article is from the "Rock Owl" blog, please be sure to keep this source http://yaoyaolx.blog.51cto.com/10732111/1728067

C Language: Macros inside the parameters are error-prone, when used as far as possible parentheses and examples

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.