Goal c: Using #define constants in math expressions

I'm new to iPhone design, and I'm just trying to follow some simple drawing procedures, and I'm having problems using certain values ​​in simple math.

I have a line like this:

int offset = (((myValue - min_value) * 6) - middle); 

and it works fine, but I don't like to use hard-coded 6 there (because I will use it a lot of places.

So, I thought I would define a constant using #define:

 #define WIDTH_OFFSET 6; 

then I could use:

 int offset = (((myValue - min_value) * WIDTH_OFFSET) - middle); 

however - this gets a compiler error: "Expected Expression".

I can get around this by breaking the calculations into several lines:

 int offset = myValue - min_value; offset = offset * WIDTH_OFFSET; offset = offset - middle; 

The compiler thinks this is normal.

I assume that there is some implicit catchy or some other function of the language here - can someone explain to me what is happening?

+4
source share
4 answers

Delete semicolon ; after #define :

 #define WIDTH_OFFSET 6 

#define literally replaces its arguments, so your expression after preprocessing becomes

 (((myValue - min_value) * 6;) - middle); 

As you can see, there is a semicolon in the middle of the expression, which is a syntax error.

On the other hand, your other expression

 int offset = myValue - min_value; offset = offset * WIDTH_OFFSET; 

does not detect such a problem, since the presence of two semicolons in a line, as in

  offset = offset * 6;; 

is syntactically valid.

+14
source

When you #define something where you use it, it is exactly the same as if you typed it in yourself. So where you use WIDTH_OFFSET, you get 6; in its place - this, of course, is not your intention. So just remove the semicolon.

+4
source

As dasblinkenlight said, remove the penumbra. The explanation for this is that #defines is a literal substitution in your code. Thus, in a semi-colony, your broken code reads:

 int offset = (((myValue - min_value) * 6;) - middle); 

Work code:

 offset = offset * 6;; 

Which is syntactically accurate like ;; is actually an empty "line" of code.

+2
source

Basically, macros are convenient functions that are built into the preprocessor. So you may think that they are doing copy / paste to match the records, in your case it will replace any WIDTH_OFFSET event with 6; , therefore, like the others, remove the semicolon ; and you are all set up.

Also, when defining macros for simple mathematical functions, remember to put them in brackets ( and ) otherwise, you may get some errors in the order of the mathematical operation (for example, unintentional multiplication of parts before adding)

+2
source

Source: https://habr.com/ru/post/1392448/


All Articles