C program output

I wrote the following program in C. The result is 32. Why is this?

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define max 10+2

int main(){
    int i;
    i = max * max;
    printf("\n%d\n",i);

    return 0;
}

      

(I am learning C and relatively new to it).

+3


source to share


4 answers


#define max 10+2

      

This is a preprocessor. it is not reasonable.

This is stupid.

it just replaces the text.

max*max

      

decide

10+2*10+2

      

which the



10+(2*10)+2

      

due to operator precedence which

10 + 20 + 2

      

i.e. 32

Also, you should always avoid preprocessor macros and use static const

instead
. You may or may not want to also consider using a variable const

or enum

instead of #define

; each has its own tradeoffs, refer to a similar question: "static const" vs "# define" vs "enumeration" .

If you want to stick with the preprocessor, you can simply use:

#define max (10+2)

      

Since the parenthesized code will assume operator certainty.

+6


source


Since it max

is a macro, it expands along the text, so your code is output with:

i = 10 +2 * 10 + 2;

      

For a macro like this, you usually want to add parentheses:



#define max (10+2)

      

So your expression will expand to:

i = (10+2) * (10+2);

      

+2


source


The compiler sees this

i = 10 + 2*10 +2 = 32

      

You should make your macro definition like this

#define max (10+2)

      

+1


source


Operator priority is a funny thing. PEMDAS = Parenthises, Exponents, Multiply, Divide, Add, Subtract.

This will resolve to be 10 + (2 * 10) + 2. First 10 * 2, which is 20.

He now reads 10 + 20 + 2. The rest should be clear.

You must exercise control over your arithmetic as needed.

0


source







All Articles