I want to print output if OUT is 1. So i think that code.
#define OUT 1
void d_printf(char *text){
if(OUT)
printf("%s", text);
}
int main(void){
d_printf("%d\n", 5);
return 0;
}
But my parametre is char*, i can't send %d, 5. How can i solve this?
You can use a simple macro:
#include <stdio.h>
#define OUT 1
#define d_printf OUT && printf
int main(void) {
d_printf("%d\n", 5);
return 0;
}
If you get compiler warnings about an unused expression, you can use a more elaborate macro:
#include <stdio.h>
#define OUT 1
#define d_printf(...) do { if (OUT) printf(__VA_ARGS__); } while(0)
int main(void) {
d_printf("%d\n", 5);
return 0;
}
Related
Having this #define PRINTF(...) printf(__VA_ARGS__) I want to create a macro that calls PRINTF but that adds prefix to the printed string, for example:
#define PRINTF_P(<args>) PRINTF(<whatever>)
// let's suppose that the desired prefix is 'prefix - '
PRINTF_P("Hello world\n");
PRINTF_P("Hello world, num = %d\n", 25);
// Result:
prefix - Hello world
prefix - Hello world, num = 20
How can I do this?
What I have tried
The following works for calls like PRINTF_P("string with argument %d\n", arg), but it doesn't for calls like `PRINTF_P("string with no argument\n");
#include <stdio.h>
#include <stdarg.h>
#define PRINTF(...) printf(__VA_ARGS__)
#define A(fmt, ...) fmt
#define B(fmt, ...) __VA_ARGS__
#define PRINTF_P(...) printf( "prefix - " A(__VA_ARGS__), B(__VA_ARGS__))
int main(void)
{
PRINTF_P("No number\n"); // This fails
PRINTF_P("Number = %d\n", 20); // This works
return 0;
}
EDIT
I'm referring only to the case of string literals, not char *.
It is as easy as:
#include <stdio.h>
#include <stdarg.h>
#define PRINTF(...) printf(__VA_ARGS__)
#define PRINTF_P(...) printf( "prefix " __VA_ARGS__)
int main(void)
{
PRINTF("No number\n");
PRINTF("Number = %d\n", 20);
PRINTF_P("No number\n");
PRINTF_P("Number = %d\n", 20);
return 0;
}
I'm not sure why you should use a macro at all.
Just write an encapsulating function using vprintf and variable args.
IDEOne Link
#include <stdarg.h>
int prefix_printf(const char* fmt, ...)
{
printf("prefix "); // Print desired Prefix
va_list args; // Declare a variable for the "..."
va_start(args, fmt); // Initialize the args as everything after parameter "fmt"
int result = vprintf(fmt, args); // Variant of printf that accepts args instead of ...
va_end(args); // Clean up the args
return result; // Return the same value printf would've returned
}
int main(void) {
prefix_printf("No number\n");
prefix_printf("Number = %d\n", 20);
return 0;
}
Result:
Success #stdin #stdout 0.01s 5536KB
prefix No number
prefix Number = 20
i searched online everywhere but i was unable to find a solution that i could implement in my code, i have some limiting factors to take in accounts, the biggest one is: i cannot use pointers to do this, second one is that i cannot edit before the comment
what i have to do is look for the SEC_B sequence in the adn1 string then save the position of it into a int array to then print it something like this:
Found sequence GTC in: 20 62 69 159 167 196
and yes i did count them manually
i have to do the same with the other sequences, but that doesn't matter as long is i can get it working with one, i can then make it work with all the others
so this is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SECUENCIA0 "TGGCGTTTGCAGATTACTGCGTCCCTCACAAGGGTGTGAA"
#define SECUENCIA1 "GCTGTGCATTCGCGGCACAAGAGTCCCGGGTCCCTGTAGC"
#define SECUENCIA2 "TTCACCATCCTGTTGTACCTATCAAACCTACCTACAGCTT"
#define SECUENCIA3 "AGTGAAGGATTATGCGATTGGCGAGCATAGTACCGGCCCG"
#define SECUENCIA4 "TCACACCGTCTCATTGGTGGCCGACCTTGGAACTCCGTCA"
#define SEC_B "GTC"
#define SEC_D "GAT"
#define SEC_K "GT"
int main()
{
char adn1[201];
adn1[0]='\0';
strcat(adn1,SECUENCIA0);
strcat(adn1,SECUENCIA1);
strcat(adn1,SECUENCIA2);
strcat(adn1,SECUENCIA3);
strcat(adn1,SECUENCIA4);
//edit from here
return 0;
}
this solution doesn't involve any explicit pointers (no * anywhere) and doesn't edit the line above the comment, i managed to come up with this solution thanks to the answer of zazz (which he deleted for some reson), here's how i've done it
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SECUENCIA0 "TGGCGTTTGCAGATTACTGCGTCCCTCACAAGGGTGTGAA"
#define SECUENCIA1 "GCTGTGCATTCGCGGCACAAGAGTCCCGGGTCCCTGTAGC"
#define SECUENCIA2 "TTCACCATCCTGTTGTACCTATCAAACCTACCTACAGCTT"
#define SECUENCIA3 "AGTGAAGGATTATGCGATTGGCGAGCATAGTACCGGCCCG"
#define SECUENCIA4 "TCACACCGTCTCATTGGTGGCCGACCTTGGAACTCCGTCA"
#define SEC_B "GTC"
#define SEC_D "GAT"
#define SEC_K "GT"
int main()
{
char adn1[201];
adn1[0]='\0';
strcat(adn1,SECUENCIA0);
strcat(adn1,SECUENCIA1);
strcat(adn1,SECUENCIA2);
strcat(adn1,SECUENCIA3);
strcat(adn1,SECUENCIA4);
//edit below here
printf("---- Búsqueda de secuencias B, D y K dentro del adn1 ------\n");
int PosicionesB[20];
int bs = 0;
int i, l1, l2;
l1 = strlen(adn1);
l2 = strlen(SEC_B);
for(i = 0; i < l1 - l2 + 1; i++) {
if(strstr(adn1 + i, SEC_B) == adn1 + i) {
PosicionesB[bs] = i;
bs++;
i = i + l2 -1;
}
}
printf("Found sequence GTC in:");
for(int i = 0; i < bs;i++){
printf(" %d",PosicionesB[i]);
}
return 0;
}
It's as simple as this:
#include <stdio.h>
#include <stdint.h>
#include <string.h>
void print_indices_substr(const char *str, const char *substr)
{
char *pstr;
printf("Indices: { ");
for (pstr = (char *)str; (pstr = strstr(pstr, substr)) != NULL; pstr = &pstr[1])
printf("%lu, ", (uintptr_t)pstr - (uintptr_t)str);
printf("}\n");
}
Basically, the function strstr returns a pointer to the first occurrence of 'substr' in 'str' or NULL if no occurrence was found. We can use this pointer in a for loop, and the index will be pstr - str, as you can see in the function above. Example:
int main()
{
const char my_string[] = "ABCDABCD";
print_indices_substr(my_string, "ABCD");
return 0;
}
Output:
Indices: { 0, 4, }
Can i compare#definevarible andchar * in strcmp as below.
#include<stdio.h>
#include<string.h>
#define var "hello"
int main()
{
char *p ="hello";
if(strcmp(p,var)==0)
printf("same\n");
else
printf("not same\n");
return 0;
}
Is there any risk comapre #define with char *as above example?
Don't trust us, trust the preprocessor output
File "foo.c"
#include <stdio.h>
#include <string.h>
#define var "hello"
int main(void)
{
char *buf="hello";
if(strcmp(buf,var)==0) // Is this good
printf("same");
return 0;
}
now:
gcc -E foo.c
lots of output because of standard system libraries then...:
# 5 "foo.c"
int main(void)
{
char *buf="hello";
if(strcmp(buf,"hello")==0)
printf("same");
return 0;
}
as you see your define has been safely replaced by the string literal.
When you have a doubt, just apply this method to make sure (more useful when converting to strings or concatenating tokens, there are traps to avoid)
In your case, you could also avoid the macro and use:
static const char *var = "hello";
which guarantees that only 1 occurrence of "hello" is set (saves data memory).
No, there is no risk to comapre #define with char* at all.
#include <stdio.h>
#include <string.h>
#define var "hello"
int main(void)
{
char *buf="hello";
if(strcmp(buf,var)==0) // Is this good
printf("same");
return 0;
}
I have a header file (generalfunctions.h):
#ifndef GENERALFUNCTIONS_H
#define GENERALFUNCTIONS_H
//functionsdeclartion for example
int getInt(char* text);
#endif /* GENERALFUNCTIONS_H */
and a C file generalfunctions.c where I include this headerfile (so I can use some of the functions within each other and don't have bother with their order) and code out the functions.
generalfunctions.c:
#include "generalfunctions.h"
#include <stdlib.h>
#include <stdio.h>
//functions implentaion for example
int getInt(char* text){
int i;
printf("%s\n", text);
if(scanf("%d", &i)==EOF){
printf("INT_ERROR\n");
exit(1);
}
while (fgetc(stdin) != '\n');
return i;
}
//...
Now I need some of these functions in a file called project_objects.c that together with project_objects.h defines a couple of structs, unions, variables and functions with these things I need for my project.
project_objects.h:
#ifndef POINT_H
#define POINT_H
typedef struct point{
int x;
int y;
} point;
point create_point(void);
void print_point(point *p);
//...
#endif /* POINT_H */
project_objects.c:
#include <stdlib.h>
#include <stdio.h>
#include "project_objects.h"
#include "generalfunctions.h"
point create_point(void){
point p;
p.x=getInt("Give my a x");
p.y=getInt("Give my a y");
return p;
}
void print_point(point *p){
printf("x: %d\n", p->x);
printf("y: %d\n", p->y);
}
//..
However I also need some of the functions described in generalfunctions.h directly in my main program:
#include "generalfunctions.c"
#include "project_objects.c"
#include <stdlib.h>
#include <stdio.h>
int main(void){
int i=getInt("How many points would you like to create?");
while(i<1){
i=getInt("Cannot create a negative number of points. How many points would you like to create?");
}
point pointarray[i];
for(int j=0; j<i; j++){
pointarray[j]=create_point();
}
for(int k=0; k<i; k++){
printf("Point %d:\n", k+1);
print_point(pointarray+k);
}
return EXIT_SUCCESS;
}
This seems to work. If I just include the h-files than I get the error that getInt() isn't defined when I link. And before when I included the C file for general functions in project_object.c I got errors for duplication. But now the files seem more dependent on each other than I planned. I also don't understand why this works.
Do not include .c-files. Write function protytypes in .h-files and include them.
project_object.h
typedef int faa;
foo.h
include "project_object.h"
faa foo( faa x ); // prototype for function "foo"
foo.c
#include "foo.h"
faa foo( faa x ) // implementation of function "foo"
{
return x + 666;
}
main.c
#include "project_object.h"
#include "foo.h" // include .h-file with prototype of function "foo"
int main( void )
{
faa x;
x = foo(0); // call function "foo"
return 0;
}
I wrote a simple program to change addition to multiplication
#include<stdio.h>
#define ADD(X,Y) X+Y
void fun()
{
#ifndef ADD(X,Y)
printf("entered #ifndef");
#define ADD(X,Y) X*Y;
#endif
int y=ADD(3,2);
printf("%d",y);
}
int main()
{
#undef ADD(X,Y)
fun();
return 0;
}
The output I expect is 3*2 but the code still outputs 3+2 i.e. 5 .
The code doesn't output : "entered #ifndef", that means #undef is not working?
What is wrong here?
Edit :
Thanks to #deviantfan
Here is the correct code:
#include<stdio.h>
#define ADD(X,Y) X+Y
void fun();
int main()
{
#undef ADD(X,Y)
fun();
return 0;
}
void fun()
{
#ifndef ADD(X,Y)
printf("entered #ifndef");
#define ADD(X,Y) X*Y;
#endif
int y=ADD(3,2);
printf("%d",y);
}
The preprocessor (which processes eg #define) doesn´t know about
functions or things like that. It processes the file strictly from top to bottom,
independent how the actual code execution would jump around at runtime.
As soon as it hits your #undef, the #ifndef is long forgotten and won´t be evaluated again.
The actual solution to this problem is to use function pointers.
Here is a direct translation from your current code to function pointers.
Note the similarities and differences.
#include <stdio.h>
int actual_add(int X, int Y) {
return X+Y;
}
int actual_multiply(int X, int Y) {
return X*Y;
}
int (*ADD)(int,int) = actual_add;
void fun()
{
if (!ADD)
{
printf("entered #ifndef");
ADD = actual_multiply;
}
int y=ADD(3,2);
printf("%d",y);
}
int main()
{
ADD = NULL;
fun();
return 0;
}
The #ifdef, #ifndef and #undef preprocessor directives expect an identifier, not an expression.
#ifndef ADD(X,Y) is meaningless.
It should read: #ifdef ADD.
The same goes for #undef ADD