Can we define boolean without a value?
To use Boolean variables in C you need to #include <stdbool.h> in your headers.
You can very much define a boolean variable without a value, as evidenced by the following code (but note the second header include, see below for explanation):
#include <stdio.h>
#include <stdbool.h>
int main (void) {
bool u, t = true, f = false;
if (t) puts("t is true"); else puts("t is false");
if (f) puts("f is true"); else puts("f is false");
if (u) puts("u is true"); else puts("u is false");
return 0;
}
This outputs (for me):
t is true
f is false
u is false
However, you should be aware of the normal rules regarding initialisation of variables where you don't make it explicit. In the code given, u will hold some arbitrary value and, indeed, using a higher warning level of gcc makes that clear:
prog.c: In function ‘main’:
prog.c:8:8: warning: ‘u’ is used uninitialized in this function [-Wuninitialized]
8 | if (u) puts("u is true"); else puts("u is false");
| ^
Note that, if you want to use bool, true, and false, these are not keywords, they're instead defined in the stdbool header file so you need to include that.
Otherwise all you get is the _Bool type(1) and neither of the nice constants, so you'll have to define some yourself or use 0 and 1 (although any non-zero value converts to 1).
Since this is scarcely a step up for doing the same thing with int, you probably want to do it properly (i.e., use the header).
Note further that this is only available as of C99. The presence of an #include <conio.h> in your code may indicate that you're using a hideously outdated implementation of C (it was a common header for DOS-era compilers such as Turbo C).
If that is the case, it's likely you don't even have a stdbool header that you can use, so you'll have to stick with int, 0, and 1.
Alternatively, you may be able to create your own my_stdbool.h such as the following, assuming there's no naming conflict as previously mentioned (most code I've seen that defines the constants tends to use the upper-case FALSE and TRUE in keeping with commonly-used guidelines):
#ifndef XYZZY_STDBOOL_H_INCLUDED
#define XYZZY_STD_BOOL_H_INCLUDED
typedef bool int;
#define false 0
#define true 1
#endif
(1) Uglier, yes, but it ensures there's no clash between code that may have been written before this became part of the standard since names beginning with _X (where X is any upper-case letter or another _) are reserved for the implementation. Hence you shouldn't be using them.
In C, you can declare a boolean variable using the _Bool type. Following as an example. However, it is not a recommended method.
#include <stdio.h>
int main()
{
printf("Hello, World!\n");
_Bool k=0, l = 1, m = 324234;
printf("%d\n", k);
printf("%d\n", l);
printf("%d\n", m);
return 0;
}
You can further use a macro to define _Bool as bool.
#include <stdio.h>
typedef _Bool bool;
int main()
{
printf("Hello, World!\n");
bool k=0, l = 1, m = 324234;
printf("%d\n", k);
printf("%d\n", l);
printf("%d\n", m);
return 0;
}
Related
This questions is about my homework.
This topic is need to use like:
#define GENERIC_MAX(type)\
type type##_max(type x, type y)\
{\
return x > y ? x : y;\
}
The content of the question is to make this code run normally:
#include <stdio.h>
GenerateShowValueFunc(double)
GenerateShowValueFunc(int)
int main()
{
double i = 5.2;
int j = 3;
showValue_double(i);
showValue_int(j);
}
The result of the operation is like this:
i=5.2000
j=3
And this code is my current progress, but there are have problems:
#include <stdio.h>
#define printname(n) printf(#n);
#define GenerateShowValueFunc(type)\
type showValue_##type(type x)\
{\
printname(x);\
printf("=%d\n", x);\
return 0;\
}
GenerateShowValueFunc(double)
GenerateShowValueFunc(int)
int main()
{
double i = 5.2;
int j = 3;
showValue_double(i);
showValue_int(j);
}
I don’t know how to make the output change with the type, and I don’t know how to display the name of the variable. OAO
This original task description:
Please refer to ShowValue.c below:
#include <stdio.h>
GenerateShowValueFunc(double)
GenerateShowValueFunc(int)
int main()
{
double i = 5.2;
int j = 3;
showValue_double(i);
showValue_int(j);
}
Through [GenerateShowValueFunc(double)] and [GenerateShowValueFunc(int)] these two lines macro call, can help us to generated as [showValue_double( double )] and [showValue_int( int )] function, And in main() function called. The execution result of this program is as follows:
i=5.2000
j=3
Please insert the code that defines GenerateShowValueFunc macro into the appropriate place in the ShowValue.c program, so that this program can compile and run smoothly.
A quick & dirty solution would be:
type showValue_##type(type x)\
{\
const char* double_fmt = "=%f\n";\
const char* int_fmt = "=%d\n";\
printname(x);\
printf(type##_fmt, x);\
return 0;\
}
The compiler will optimize out the variable that isn't used, so it won't affect performance. But it might yield warnings "variable not used". You can add null statements like (void)double_fmt; to silence it.
Anyway, this is all very brittle and bug-prone, it was never recommended practice to write macros like these. And it is not how you do generic programming in modern C. You can teach your teacher how, by showing them the following example:
#include <stdio.h>
void double_show (double d)
{
printf("%f\n", d);
}
void int_show (int i)
{
printf("%d\n", i);
}
#define show(x) _Generic((x),\
double: double_show, \
int: int_show) (x) // the x here is the parameter passed to the function
int main()
{
double i = 5.2;
int j = 3;
show(i);
show(j);
}
This uses the modern C11/C17 standard _Generic keyword, which can check for types at compile-time. The macro picks the appropriate function to call and it is type safe. The caller doesn't need to worry which "show" function to call nor that they pass the correct type.
Without changing the shown C-code (i.e. only doing macros), which I consider a requirement, the following code has the required output:
#include <stdio.h>
#define showValue_double(input) \
showValueFunc_double(#input"=%.4f\n" , input)
#define showValue_int(input) \
showValueFunc_int(#input"=%d\n" , input)
#define GenerateShowValueFunc(type) \
void showValueFunc_##type(const char format[], type input)\
{\
printf(format, input); \
}
/* ... macro magic above; */
/* unchangeable code below ... */
GenerateShowValueFunc(double)
GenerateShowValueFunc(int)
int main()
{
double i = 5.2;
int j = 3;
showValue_double(i);
showValue_int(j);
}
Output:
i=5.2000
j=3
Note that I created something of a lookup-table for type-specific format specifiers. I.e. for each type to be supported you need to add a macro #define showValue_ .... This is also needed to get the name of the variable into the output.
This uses the fact that two "strings" are concatenated by C compilers, i.e. "A""B" is the same as "AB". Where "A" is the result of #input.
The rest, i.e. the required function definition is very similar to the teacher-provided example, using the ## operator.
Note, this is if the variable name has to correctly be mentioned in the output.
With out the i = things would be easier and would more elegantly use the generated functions WITHOUT having the called showValue_double(i); be explicit macros. I.e. the functions generated are 1:1 what is called from main(). I think that might be what is really asked. Let me know if you want that version.
_Generic can select between different statements based on the type of the variable passed, however (as somewhat expected) it fails if these statements contain type names themselves. As an example:
#define PROMOTE(var) \
_Generic((var), \
char: int);
int main() {
char c;
PROMOTE(c) i = 0;
return 0;
}
One might expect the above code to work, with the line using PROMOTE evaluating to "int i = 0", but alas, it does not compile. I tried some roundabout ways to write the type (int), such as with a macro (#define TYPE_int int) or a typedef (typedef int TYPE_int), but to no avail. This is most probably intended (or purposefully undefined) behavior, but I'm still interested in the possibility, even if it requires some C wizardry.
In light of that, how can one make _Generic output a type?
Note: Solutions should rely only on standard C (i.e. no compiler specific constructs).
The closest thing I can imagine is combination of _Generic, compound literals and typeof extension available in popular compilers like GCC and CLANG.
#include <stdio.h>
struct SomeStruct { int x; };
#define PROMOTE(X) typeof(_Generic((X){0}, char: (int){0}, int: (float){0}, float: (struct SomeStruct){0}))
int main() {
PROMOTE(char) a = 1;
PROMOTE(int) b = 2.0f;
PROMOTE(float) c = { .x = 42 };
printf("%d\n", a);
printf("%f\n", b);
printf("%d\n", c.x);
return 0;
}
prints
1
2.000000
42
Unfortunately, This is not standard C.
While making a function atof, I splitted the entire work into two separate translational units:
m.c
#include<stdio.h>
extern fun(char[]); //return type not mentioned on purpose
int main()
{
printf("%d\n",fun("+123.980")); //%f would also display 0.000000
return 0;
}
n.c
#include<ctype.h>
float fun(char c[])
{
float val=0, pow=1;
int i;
int sign;
for(i=0;isspace(c[i]);i++); //SKIPPING WHITESPACE IF ANY
if(c[i]=='+')
sign = 1;
if(c[i]=='-')
sign =-1;
++i;
for(;c[i]!='.';i++)
val = val*10 + (c[i]-'0');
++i;
while(isdigit(c[i]))
{
val = val*10 + (c[i]-'0');
pow=pow*10;
++i;
}
return sign*val/pow;
}
The warning says that the type of function will default to int in this case since every variable/function type at global space without any return type mentioned explicitly defaults to int.
I was expecting the output to be int version of +123.980 i.e 123 only.
But instead it shows 0 (otherwise function works fine). Why?
Implicit int and implicit function declarations are removed from the C language. They are no more. The program is ill-formed. If your compiler accepts it, then you are dealing with a vendor extension — or a compiler for an outdated version of C.
Before these things were removed, the program had undefined behaviour. All editions of the standard require that all declarations of an entity in a program must be compatible, regardless of whether anything in them is implicit or not. Violations of this rule lead to undefined behaviour, with no diagnostic required.
I was wondering if there is any way of protecting a variable for being modified once initialized (something like "constantize" a variable at runtime ). For example:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int v, op;
scanf( "%d", &op );
if( op == 0 )
v = 1;
else
v = 2;
// here transform v to a constant...
.
.
// ...and that any attempt to modify v yields to an error.
.
.
return EXIT_SUCCESS;
}
You can make the result of the input be const like this:
int func()
{
int op = 0;
scanf( "%d", &op );
if( op == 0 )
return 1;
else
return 2;
}
int main()
{
const int v = func();
// ...
}
NB. Of course, there is no way to prevent undefined behaviour happening later in the program which appears to change v (since undefined behaviour can, by definition, have any effect).
Yes: Factor your code:
foo.h:
void do_something(int arg);
foo.c:
#include "foo.h"
void do_something(int arg)
{
// implement
//
// Here "arg" is completely under your control.
}
foo_test.c:
#include "foo.h"
// add unit tests for do_something
main.c:
#include <stdio.h>
#include <stdlib.h>
#include "foo.h"
int main(void)
{
int op;
if (scanf("%d", &op) != 1) { abort(); }
do_something(op == 0 ? 1 : 2);
}
It is now completely clear from the code that the function argument of do_something is private and local to the function and cannot be affected by anything above the call.
The only way to prevent a global variable from being modified after initialization is declaring it const:
const int i = 5;
Hoever, as shown above, this requires it to be initialized with the definition. There is no way of initialize it from program code or using other than a constant expression which is evaluated at compile-time.
Note that while you can cast the const away, this results in undefined bahaviour and very likely leads to problems as const variables might be put into a read-only memory area of your program.
If you do need access control to such a variable, you would have to put it either as static into a function (with initialization on first call), or - better a seperate module/compilation unit (also as static). Use explicit setter/getter function on this then:
"wrapper.h":
#ifndef WRAPPER_H
#define WRAPPER_H
extern void set_once(int v);
extern int get_value(void);
#endif
"wrapper.c":
#include <stdbool.h>
#include "wrapper.h"
static struct {
bool is_set; // guaranteed false on startup
int value;
} my_var;
void set_once(int v)
{
if ( !my_var.is_set )
my_var.value = v;
else
; // report an error, e.g. abort()
}
int get_value(void)
{
if ( !my_var.is_set )
return my_var.value;
// report an error, e.g. abort()
}
"main.c"
#include "wrapper.h"
int main(void)
{
set_once(5);
int i = get_value();
}
This way you will can get a runtime error if you use the value uninitialized or tries to set it more than once. Note the flag relies on global variables to be initialized to 0 (which is guaranteed to evaluate false).
Although you might just ignore multiple sets, is is good practice to catch and report, at least during debugging/testing (e.g. using assert).
Edit:
The approach above is for global variables. If multiple variables are to be protected, it can be modified such as the functions take a pointer to the struct. If different types are to be used, pack the flag into its own struct and add that as the first anonymous field to one struct type for each type to be protected. If gcc-extensions are available&allowed, have a look at -fplan9-extensions. Using opaque pointers can avoid unintended external modifications.
For local variables, however, use #MattMcNabb's version.
No, never.
You could make it const, but that's more of a light hint and can be cast away with barely any effort. Besides if you have a pointer to something you can always change it by direct memory access.
You could also hide it inside a class that manages write access to it, but you're in the same situation as the first case -- you have a pointer to it.
Is it possible to implement static_if in C99?
#define STATIC_IF(COND, ...) \
if (COND) MACRO1(__VA_ARGS__); \
else MACRO2(__VA_ARGS__);
How can I properly implement STATIC_IF(…) in here? Depending on COND the arguments either should be passed to MACRO1 or MACRO2, but the arguments for both macros look differently. COND is statically testable, something like sizeof (…) > 42.
#if COND then #define STATIC_IF MACRO1 … wouldn't work for my use case.
I cannot use compiler specific solutions.
In your specific case (if I understand your comments correctly), yes, you can do this.
You can't pass sizeof to anything in the preprocessor because the preprocessor runs before type information is available. Luckily for you, you don't need sizeof to count the number of arguments in a statically-written list (X-Y alert!), so this is no obstacle.
Here's one possible implementation using the Order macro library:
#include <stdio.h>
#include <order/interpreter.h>
void oneArg(int a) {
printf("one arg: %d\n", a);
}
void twoArgs(int a, int b) {
printf("two args: %d %d\n", a, b);
}
void threeArgs(int a, int b, int c) {
printf("three args: %d %d %d\n", a, b, c);
}
#define ORDER_PP_DEF_8function_list \
ORDER_PP_CONST(("unused") \
(oneArg) \
(twoArgs) \
(threeArgs))
#define SelectFunction(...) ORDER_PP ( \
8seq_at(8tuple_size(8((__VA_ARGS__))), 8function_list) \
)
#define Overloaded(...) SelectFunction(__VA_ARGS__)(__VA_ARGS__)
int main(void) {
Overloaded(42);
Overloaded(42, 47);
Overloaded(42, 47, 64);
return 0;
}
(This simple case indexes a list by the number of arguments - probably not exactly what you want to do, but enough to get the idea. Order does provide a full range of complex, nonevaluating control structures - if, cond, match, etc. - for more complex decision-making.)
Order is pretty heavyweight: I assume you can do something similar with the much lighter and more realistically-portable P99 (not familiar with it). Order works very well with GCC and adequately well with Clang (Clang will choke on deep recursion or long loops); it is standard, but not all compilers are.
This is not possible, because a condition like sizeof(something)>42 is not static for the preprocessor. The preprocessor is purely textual (in principle, except for arithmetic). It does not know about C or types.
Notice that expression of the condition in #if is severely constrained.
However, you could use build tricks. For instance, you might have a standalone program like
// generate-sizeof.c
#include <stdio.h>
#include "foo-header.h"
int main(int argc, char**argv) {
const char* headername = NULL;
if (argc<2)
{ fprintf(stderr, "%s: missing header name\n", argv[0]);
exit(EXIT_FAILURE); };
headername = argv[1];
FILE *fh = fopen(headername, "w");
if (!fh) { perror(headername); exit(EXIT_FAILURE); };
fprintf(fp, "// generated file %s\n", headername);
fprintf(fp, "#define SIZEOF_charptr %d\n", (int) sizeof(char*));
fprintf(fp, "#define SIZEOF_Foo %d\n", (int) sizeof(Foo));
fclose (fp);
}
then have a rule like
generated-sizes.h : generate-sizeof foo-header.h
./generate-sizeof generated-sizes.h
in your Makefile etc etc...
So your build machinery will generate the appropriate headers.
Things become much tricker if you want to cross-compile!
Then you might have an #include "generated-sizes.h" in your header, and later code
#if SIZEOF_Foo > 42
#error cannot have such big Foo
#endif
I don't think so, not in the sense you mean.
But: I would just go ahead, and trust that an optimizing compiler notices that the condition is always true (or false) and does the right thing, i.e. optimizes out the test.
You might need to force some optimization to provoke the compiler into doing this.
If you can remove the restriction of having to stick to C99, there is a better solution to this problem built-in to the language since C11:
#include <stdio.h>
void f1(float x, double y, float * z) {
printf("inside f1\n");
}
void f2(int x, _Bool * y) {
printf("inside f2\n");
}
#define STATIC_IF(COND, ...) _Generic(&(int[(!!(COND))+1]){ 0 }, \
int(*)[2]: f1, \
int(*)[1]: f2) \
(__VA_ARGS__)
int main(void) {
float fl;
_Bool b;
STATIC_IF(sizeof(double) > 4, 0.0f, 1.0, &fl);
STATIC_IF(sizeof(double) > 128, 16, &b);
}
The _Generic operator performs a compile-time selection based on a type. Since it selects based on a type, it's also the only language-level expression that can accept conflicting types of "argument", since its very purpose is to resolve a value of the right type based on inputs.
This means you can easily use it to choose between your two functions with incompatible signatures, because it will completely ignore the type of the one that isn't chosen by matching the input; the arguments (applied to whichever function _Generic returns) will only be checked against the successful match.
Although _Generic is designed to dispatch on types, not values, any integer constant expression can be "turned into" a type by using it as the size of an array. So in the above macro we create an anonymous array (n.b. this is not a VLA), of count either 2 (for true) or 1 (for false) and dispatch against the type of the pointer to that array in order to resolve which of the two incompatible functions to use.
This will certainly reduce to nothing at runtime, since not only is the condition static, but the alternative "execution path" wouldn't even type check and thus can't have code generated for it in the first place.