Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an elegant way to force the comparison of two constants?

Tags:

c

As we all know, the following code will be optimized by all sensible compilers:

const int a = 3; const int b = 42;  if (a == b) {     do_something(); } 

If the two constants are the same, the if is omitted and the function always called, if they are different, the whole block is omitted.

However, there can be situations where it is important to NOT optimize this code, as the program itself can be modified before it is run. E.g. the binary sits in flash memory and can be accessed by an external program, and of course the adresses of the two consts are fixed. (makes sense in embedded).

I'm thinking of using #pragma, but that is not part of the C standard.

Another way would be to use const volatile. Is that guaranteed to work on all standard-compliant compilers?

like image 358
vsz Avatar asked Apr 23 '13 07:04

vsz


People also ask

Is there a way to compare two columns in Excel for differences?

Navigate to the "Home" option and select duplicate values in the toolbar. Next, navigate to Conditional Formatting in Excel Option. A new window will appear on the screen with options to select "Duplicate" and "Unique" values. You can compare the two columns with matching values or unique values.

How do you compare two objects?

Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity. For example, the expression obj1==obj2 tests the identity, not equality.

How do you write an IF THEN formula in Excel?

Use the IF function, one of the logical functions, to return one value if a condition is true and another value if it's false. For example: =IF(A2>B2,"Over Budget","OK") =IF(A2=B2,B4-A4,"")

How do you compare two strings for similarity or highlight differences in Excel?

On the Home tab, go to Editing group, and click Find & Select > Go To Special… Then select Row differences and click the OK button. The cells whose values are different from the comparison cell in each row are colored.


1 Answers

Yes, const volatile int a = 3; does exactly what you want, and is standards compliant from C89 onwards (See section 3.5.3 of C89).

This excellent answer describes const volatile in detail, for use in a situation similar to yours.

like image 130
Timothy Jones Avatar answered Sep 18 '22 17:09

Timothy Jones