I'm using VS 2010 Pro.
First, C doesn't have a bool type? I just have to use int with 0/1. Seems odd as most languages consider boolean a standard type.
Also I have Visual Studio 2010 Pro but doesn't have a "C Project". I just created an Empty C++ Project. The file names end with .c
The problem with this is the keywords are messed up (shows bool as highlighted/valid in the editor, but compiler doesn't like it).
I went to repair/add components and they have C#, F#, C++, Visual Basic; but no C?
Newest C standard (C99) has bool type indeed. Just include stdbool.h and you can use it. Unfortunately MSVC does not haver proper support for C at all. Only partial C89.
The current C language (C99) has a bool type (actually _Bool, but including stdbool.h declares a typedef alias bool for it), but since you're using MSVC, that's not available to you. In any case, using boolean types in C is completely non-idiomatic and largely useless. Just use int like everyone else. Or if you need a giant array of them, make your own bit-array implementation.
C did not have an actual Boolean type until C99.
As a result, idiomatic C doesn't really use boolean-valued symbols or expressions as such (i.e., you won't see many explicit tests against "true" or "false"). Instead, any zero-valued integral expression or a NULL pointer will evaluate to "false", and any non-zero-valued integral expression or a non-NULL pointer will evaluate to "true". So you'll see a lot of code like:
foo *bar = malloc(sizeof *bar * ...);
if (bar) // equivalent to writing bar != NULL
{
// bar is non-NULL
}
Relational and equality expressions such as a == b or c < d will evaluate to an integral type with a value of either 1 (true) or 0 (false).
Some people introduce their own TRUE or FALSE symbolic constants by doing something like
#define TRUE (1) // or (!FALSE), or (1==1), or...
#define FALSE (0) // or (!TRUE), or (1==0), or ...
Unforunately, some of those people occasionally manage to misspell 0 or 1 (or the expressions that are supposed to evaluate to 0 or 1); I once spent an afternoon chasing my tail because someone screwed up and dropped a header where TRUE == FALSE.
Not coincidentally, that was the day I stopped using symbolic constants for Boolean values altogether.
See R.'s answer for information about the bool type.
Unfortunately, MSVC doesn't support C99 when it's compiling C code - it has bits and pieces (generally things in the C99 library that are required by C++), but for the most part it only supports C90.
As for bool still being highlighted in the editor - the highlighting in MSVC may be sophisticated, but it doesn't take into account the differentiation between C, C++, and C++/CLI. For example, if you use a construct that's CLI-only, it'll be highlighted as such even if your project has nothing to do with CLI.
If you're developing in C, I'd recommend a different compiler as VC++ is not a modern C compilier and does not support the C99 standard. If you're on windows try MinGW, which basically gets you GCC with access to Windows-y API stuff.
If you're set on using Visual Studio, create your own header file to use instead of stdbool.h:
#pragma once
#define false 0
#define true 1
#define bool int
I found that Visual Studio 2010 complained if I tried to use a typedef instead of a #define to define bool.
Concerning the bool type:
In C, any non-zero value is regarded as "true" (and zero is "false"). This comes in handy when, say, checking the value of a pointer:
if ((ptr = malloc(sizeof(foo))) != 0) ...
can be shortened to:
if (ptr = malloc(sizeof(foo))) ...
C was designed to be a "mid-level" language, i.e. in-between assembler and traditional "high-level" languages. It was also designed to be compact/concise. So it has a minimalist flavor, exemplified in the its support for "shorthand" like the above, and also in the omission of a built-in Boolean data type (up to C99, as others have pointed out).
Many libraries/frameworks (ones that I'm aware of anyway) do something like the following
#define BOOL int
#define FALSE 0
#define TRUE (!FALSE)
This does mean that you should avoid directly comparing values/results to TRUE. Consider the following. Given int a = 2; int b = 3;, then both if (a) and if (b) evaluate to true, but a and b are not equal.
Concerning syntax highlighting:
C++ does have a bool type, which I'm guessing is why the compiler highlights the word. However, the fact that your source file ends it .c marks it as C code, so the type isn't allowed.
Seems like the syntax highlighting should catch this, though.
Concerning the absence of C components:
If I understand the question correctly: the short answer is, in order to do "managed code" (ie .NET) development -- which is what you'd have to be doing in order to use .NET components -- you need to use a language supported by the .NET runtime, i.e. C#, VB(.NET), F#, or C++.
(C++ is available in both "managed" and "unmanaged" flavors, meaning you can develop either against .NET or the Windows API.)
Are you under some sort of directive to use C as opposed to other languages?
Related
I'm getting the next MISRA error:
Rule-10.4 The operands of this equality operator are expressions of different 'essential type' categories (Boolean and unsigned).
The code is showed below:
#define TRUE (1!=0)
#define FALSE (0!=0)
typedef unsigned char boolean;
boolean active;
getActive(&active);
if (TRUE == active) <<<<<<<<<<<< HEre is the conflicting line
{
// DO Something
}
If I remove the TRUE :
if (active)
MISTA Rule 14.4 appears: "Controlling expression is not an 'essentially Boolean' expression"
So I cannot figure out the solution,
I see that using
#define TRUE 1U
#define FALSE 0U
solves the problem but I'm afraid I cannot afford this solution since I'm using a big inherited code from a 3rd party using the (1!=0) expression.
I guess that expression is more 'smart' and portable since in some systems the meaning of TRUE/ FALSE might chenge to 0/1 but I wonder if I can keep the:
#define TRUE (1!=0)
#define FALSE (0!=0)
and write my conditional expressions in a manner to cope with the MISRA issues
Your MISRA checker is unable to determine that these are your boolean type.
In case you are stuck with C90 and only then: you need to inform your tool somehow about which custom bool type you are using. Otherwise it won't be able to tell what these macros are for.
Otherwise, simply use stdbool.h. There are very few excuses not to in the year 2019.
Thanks to all for the answers and comments.
Unfortunately I'm not allowed to use stdbool.h , I'm using an AUTOSAR (automotive) stack and they don't use any of the standard libraries.
I'd prefer don't to trick the MISRA tool to indicate the boolean type, I thinkit would be something that we'd have to export to any PC of the team (ad-hoc solution)
Thanks to #R about the (1 != 0) clarification; it makes no sense , C is C (not bash or whatever where the true might be 0) , and true will be always 1, so unless you are ignorant about the bool value in your programming language the definition as a expression is useless.
I think that for my porpuses the best solution would be to redefine the macros as:
#define TRUE (1U)
#define FALSE (0U)
I've seen the AUTOSAR stack gives me the option to redefine this values in a Integration file
And this way I keep the compatibility with all my Application code and the existing AUTOSA stack and also I don't need to change anything in the inherited code.
NOTE: This is NOT a duplicate of the question linked by Paul T, because I am asking if it is possible to determine if a type is of a certain broader incomplete type/kind at compile time, not if a symbol has been registered at compile time. This seems like a fundamental misunderstanding of the question.
I am writing a library in C that deals with pseudo-generic functions which take a type as an argument through a macro wrapper.
To spare the details (because they are rather complicated) there are two possible features that could help, I think:
Being able to detect if a type is a pointer at compile time. (No, the "use _Generic to test if you get ptrdiff_t from subtraction" trick won't work, because structures are a possibility, and you can't subtract structures.)
Being able to detect if a type is a struct at compile time. (If this was possible, then the aforementioned _Generic trick could be used if the type was detected as not being a struct.)
I've tried everything I could think of on Godbolt (even trying to compare types to incomplete anonymous structs and toying with __builtin_types_compatible_p) and wasn't able to find any solutions.
If anyone has any solutions I'd love to see them, otherwise I may just end up having to complicate the design a bit-- so not the end of the world if it's impossible, but it would be ideal if it can be done.
To give a basic idea of what one of these macros might look like or their expected output:
int *a;
assert(!IS_STRUCT(a));
assert(IS_POINTER(a));
struct {} b;
assert(IS_STRUCT(b));
assert(!IS_POINTER(b));
shouldn't throw any errors.
Complete Answer (if EDG Front End used):
If your IDE / compiler is using the EDG C++ Front End (which a lot are), and you are using C, not C++ (which your tag suggests), and you say you ARE using typeof, then you can detect a structs as follows (see the latest manual, page 75):
/* Test if EDG Front End is used*/
#if defined(__EDG__) && defined(__EDG_VERSION__)
#define IS_STRUCT(expression_or_type_name) __is_class(typeof (expression_or_type_name)))
#endif
since in C __is_class() will only be true for a struct (http://www.cplusplus.com/reference/type_traits/is_class/).
Further, pointers can similarly be detected as follows:
/* Test if EDG Front End is used*/
#if defined(__EDG__) && defined(__EDG_VERSION__)
#define IS_POINTER(expression_or_type_name) (__is_convertible_to(typeof (expression_or_type_name), void*) || __is_convertible_to(typeof (expression_or_type_name), void const*) || __is_convertible_to(typeof (expression_or_type_name), void volatile*) || __is_convertible_to(typeof (expression_or_type_name), void const volatile*))
#endif
(http://www.cplusplus.com/reference/type_traits/is_convertible/)
It’s not possible in standard C. Whatever solutions there may be must be implementation-defined.
It seems that C is not a suitable language for your problem domain. Short of esoteric platforms that come without C++ support, there seems to be little reason to have to solve this in C. On most any platform where C is available, so is C++. Since you claim that you use gcc, then C++ is surely available and you can process some of the input using a C++ compiler. You could do the input processing as a generator step: run the code through a C++ compiler to generate source code that defines constants that capture type properties sought.
Any time I had the need of a Boolean type I was told to either create one, or better yet, use stdbool.h.
Since stdbool.h uses typedef bool _Bool, is there a reason to use the header instead just using type _Bool? Is it just for the additional macros (/* #define true 1 #define false 0 */)?
The obvious type to add into the language was bool. But unfortunately, plenty of code was written that included bool in other shapes and forms. Recall that support for a boolean type was added only in C99.
So the C language committee had no choice but to pull out a reserved identifier for it (_Bool). But, since the obvious choice of type name is still the same, stdbool.h was added to allow users the obvious name. That way, if your code didn't have a home-brewed bool, you could use the built in one.
So do indeed use stdbool.h if you aren't bound to some existing home-brewed bool. It will be the standard type, with all the benefits that type brings in.
The common practice has always been to use bool but when the type was officially introduced into the standard in C99, they didn't want to break the "roll-your-own" implementations. So they made the type _Bool as kind of a hack around the unofficial bools. Now there's no type name collision. Anyway, point is, use bool unless a legacy codebase breaks.
They are same. bool is an alias for _Bool.
Before C99 we used we dont have this type. (Earlier the use was limited to an integer tyoe with 0 as false and 1 as true).
You may not use it. Even you can undef bool (but it is recommended not to do so). But including it (stdbool.h and bool alias of _Bool) is good because then if someday it becomes reserved your code complies to that.1
1. You can use bool other way but it is better not to. Because in general when this stdbool.h is introduced it bears the plan of gradually making it standard and then even more stricter rule applies where we can't use bool as something other and it will be reserved as keyword.
I am trying to calculate the Greatest Common Denominator of two integers.
C Code:
#include <stdio.h>
int gcd(int x, int y);
int main()
{
int m,n,temp;
printf("Enter two integers: \n");
scanf("%d%d",&m,&n);
printf("GCD of %d & %d is = %d",m,n,gcd(m,n));
return 0;
}
int gcd(int x, int y)
{
int i,j,temp1,temp2;
for(i =1; i <= (x<y ? x:y); i++)
{
temp1 = x%i;
temp2 = y%i;
if(temp1 ==0 and temp2 == 0)
j = i;
}
return j;
}
In the if statement, note the logical operator. It is and not && (by mistake). The code works without any warning or error.
Is there an and operator in C? I am using orwellDev-C++ 5.4.2 (in c99 mode).
&& and and are alternate tokens and are functionally same, from section 2.6 Alternative tokens from the C++ draft standard:
Alternative Primary
and &&
Is one of the entries in the Table 2 - Alternative tokens and it says in subsection 2:
In all respects of the language, each alternative token behaves the same, respectively, as its primary token, except for its spelling. The set of alternative tokens is defined in Table 2.
As Potatoswatter points out, using and will most likely confuse most people, so it is probably better to stick with &&.
Important to note that in Visual Studio is not complaint in C++ and apparently does not plan to be.
Edit
I am adding a C specific answer since this was originally an answer to a C++ question but was merged I am adding the relevant quote from the C99 draft standard which is section 7.9 Alternative spellings <iso646.h> paragraph 1 says:
The header defines the following eleven macros (on the left) that expand
to the corresponding tokens (on the right):
and includes this line as well as several others:
and &&
We can also find a good reference here.
Update
Looking at your latest code update, I am not sure that you are really compiling in C mode, the release notes for OrwellDev 5.4.2 say it is using GCC 4.7.2. I can not get this to build in either gcc-4.7 nor gcc-4.8 using -x c to put into C language mode, see the live code here. Although if you comment the gcc line and use g++ it builds ok. It also builds ok under gcc if you uncomment #include <iso646.h>
Check out the page here iso646.h
This header defines 11 macro's that are the text equivalents of some common operators.
and is one of the defines.
Note that I can only test this for a C++ compiler so I'm not certain if you can use this with a strict C compiler.
EDIT I've just tested it with a C compiler here and it does work.
and is just an alternative token for &&.
We can easily quote the standard here :
2.6 Alternative tokens [lex.digraph]
In all respects of the language, each alternative token behaves the same, respectively, as its primary token, except for its spelling. The set of alternative tokens is defined in Table 2.
In table 2 :
Alternative | Primary
and | &&
But I suggest you to use &&. People used to C/C++ may get confused by and...
Since it is merged now, we are talking also about C, you can check this page ciso646 defining the alternatives tokens.
This header defines 11 macro constants with alternative spellings for those C++ operators not supported by the ISO646 standard character set.
From the C99 draft standard :
7.9 Alternative spellings <iso646.h>
The header defines the following eleven macros (on the left) that expand
to the corresponding tokens (on the right):
and &&
Basically and is just the text version of && in c.
You do however need to #include <iso646.h>. or it isn't going to compile.
You can read more here:
http://msdn.microsoft.com/en-us/library/c6s3h5a7%28v=vs.80%29.aspx
If the code in your question compiles without errors, either you're not really compiling in C99 mode or (less likely) your compiler is buggy. Or the code is incomplete, and there's a #include <iso646.h> that you haven't shown us.
Most likely you're actually invoking your compiler in C++ mode. To test this, try adding a declaration like:
int class;
A C compiler will accept this; a C++ compiler will reject it as a syntax error, since class is a keyword. (This may be a bit more reliable than testing the __cplusplus macro; a misconfigured development system could conceivably invoke a C++ compiler with the preprocessor in C mode.)
In C99, the header <iso646.h> defines 11 macros that provide alternative spellings for certain operators. One of these is
#define and &&
So you can write
if(temp1 ==0 and temp2 == 0)
in C only if you have a #include <iso646.h>; otherwise it's a syntax error.
<iso646.h> was added to the language by the 1995 amendment to the 1990 ISO C standard, so you don't even need a C99-compliant compiler to use it.
In C++, the header is unnecessary; the same tokens defined as macros by C's <iso646.h> are built-in alternative spellings. (They're defined in the same section of the C++ standard, 2.6 [lex.digraph], as the digraphs, but a footnote clarifies that the term "digraph" doesn't apply to lexical keywords like and.) As the C++ standard says:
In all respects of the language, each alternative token behaves the
same, respectively, as its primary token, except for its spelling.
You could use #include <ciso646> in a C++ program, but there's no point in doing so (though it will affect the behavior of #ifdef and).
I actually wouldn't advise using the alternative tokens, either in C or in C++, unless you really need to (say, in the very rare case where you're on a system where you can't easily enter the & character). Though they're more readable to non-programmers, they're likely to be less readable to someone with a decent knowledge of the C and/or C++ language -- as demonstrated by the fact that you had to ask this question.
It is compiling to you because I think you included iso646.h(ciso646.h) header file.
According to it and is identical to &&. If you don't include that it gives compiler error.
The and operator is the text equivalent of && Ref- AND Operator
The or operator is the text equivalent of || Ref.- OR Operator
So resA and resB are identical.
&& and and are synonyms and mean Logical AND in C++. For more info check Logical Operators in C++ and Operator Synonyms in C++.
In C, shall I prefer constants over defines? I've reading a lot of code lately, and all of the examples make heavy use of defines.
No, in general you should not use const-qualified objects in C to create names constants. In order to create a named constant in C you should use either macros (#define) or enums. In fact, C language has no constants, in the sense that you seem to imply. (C is significantly different from C++ in this regard)
In C language the notions of constant and constant expression are defined very differently from C++. In C constant means a literal value, like 123. Here are some examples of constants in C
123
34.58
'x'
Constants in C can be used to build constant expressions. However, since const-qualified objects of any type are not a constants in C, they cannot be used in constant expressions, and, consequently, you cannot use const-qualified objects where constant expressions are required.
For example, the following is not a constant
const int C = 123; /* C is not a constant!!! */
and since the above C is not a constant, it cannot be used to declare an array type in file scope
typedef int TArray[C]; /* ERROR: constant expression required */
It cannot be used as a case label
switch (i) {
case C: ; /* ERROR: constant expression required */
}
It cannot be used as bit-field width
struct S {
int f : C; /* ERROR: constant expression required */
};
It cannot be used as an initializer for an object with static storage duration
static int i = C; /* ERROR: constant expression required */
It cannot be used as a enum initializer
enum {
E = C /* ERROR: constant expression required */
};
i.e it cannot be used anywhere where a constant is required.
This might seem counter-intuitive, but this is how C the language is defined.
This is why you see these numerous #define-s in the code you are working with. Again, in C language const-qualified object have very limited use. They are basically completely useless as "constants", which is why in C language you are basically forced to use #define or enums to declare true constants.
Of course, in situations when a const-qualified object works for you, i.e. it does what you want it to do, it is indeed superior to macros in many ways, since it is scoped and typed. You should probably prefer such objects where applicable, however in general case you'll have to take into account the above limitations.
Constants should be preferred over defines. There are several advantages:
Type safety. While C is a weakly typed languaged, using a define loses all of the type safety, which will allow the compiler to pick up problems for you.
Ease of debugging. You can change the value of constants through the debugger, while defines are automatically changed in the code by the pre-processor to the actual value, meaning that if you want to change the value for test/debugging purposes, you need to re-compile.
Maybe I have been using them wrong but, at least in gcc, you can't use constants in case statements.
const int A=12;
switch (argc) {
case A:
break;
}
Though this question is specific to C, I guess it is good to know this:
#include<stdio.h>
int main() {
const int CON = 123;
int* A = &CON;
(*A)++;
printf("%d\n", CON); // 124 in C
}
works in C, but not in C++
One of the reasons to use #define is to avoid such things to mess up your code, specially it is a mix of C and C++.
A lot of people here are giving you "C++ style" advice. Some even say the C++ arguments apply to C. That may be a fair point. (Whether it is or not feels kind of subjective.) The people who say const sometimes means something different in the two languages are also correct.
But these are mostly minor points and personally, I think in truth there is relatively minor consequence to going either way. It's a matter of style, and I think different groups of people will give you different answers.
In terms of common usage, historical usage, and most common style, in C, it's a lot more typical to see #define. Using C++isms in C code can come off as strange to a certain narrow segment of C coders. (Including me, so that's where my biases lie.)
But I'm surprised no one has suggested a middle ground solution, that "feels right" in both languages: if it fits into a group of integer constants, use an enum.
define can be used for many purposes(very loose) and should be avoided if you can substitute that with const, which define a variable and you can do a lot more with it.
In cases like below, define has to be used
directive switch
substitution to your source line
code macros
An example where you have to use define over const is when you have version number say 3 and you want version 4 to include some methods that is not available in version 3
#define VERSION 4
...
#if VERSION==4
................
#endif
Defines have been part of the language longer than constants, so a lot of older code will use them because defines where the only way to get the job done when the code was written. For more recent code it may be simply a matter of programmer habit.
Constants have a type as well as a value, so they would be preferred when it makes sense for your value to have a type, but not when it is typeless (or polymorphic).
If it's something that isn't determined programmatically, I use #define. For example, if I want all of my UI objects to have the same space between them, I might use #define kGUISpace 20.
Apart from the excellent reasons given by AndreyT for using DEFINES rather than constants in "C" code there is another more pragmatic reason for using DEFINES.
DEFINES are easy define and use from (.h) header files, which is where any experienced C coder would expect to find constants defined. Defining consts in header files is not quite so easy -- its more code to avoid duplicate definitions etc.
Also the "typesafe" arguments are moot most compilers will pick up glaring errors suchh as assing a string to and int, or, will "do the right thing" on a slight mismatch such as assigning an integer to a float.
Macros (defines) can be used by the pre-processor and at compile time, constants cannot.
You can do compile-time checks to make sure a macro is within a valid range (and #error or #fatal if it isn't). You can use default values for a macro if it hasn't already been defined. You can use a macro in the size of an array.
A compiler can optimize with macros better than it can with constants:
const int SIZE_A = 15;
#define SIZE_B 15
for (i = 0; i < SIZE_A + 1; ++i); // if not optimized may load A and add 1 on each pass
for (i = 0; i < SIZE_B + 1; ++i); // compiler will replace "SIZE_B + 1" with 16
Most of my work is with embedded processors that don't have amazing optimizing compilers. Maybe gcc will treat SIZE_A like a macro at some optimization level.