c,if-statement,macros,conditional , Macro for run-once conditioning


Macro for run-once conditioning

Question:

Tag: c,if-statement,macros,conditional

I am trying to build a macro that runs a code only once. Very useful for example if you loop a code and want something inside to happen only once. The easy to use method:

static int checksum;

for( ; ; )
{
    if(checksum == 0) { checksum == 1; // ... }
}

But it is a bit wasteful and confusing. So I have this macros that use checking bits instead of checking true/false state of a variable:

#define CHECKSUM(d) static d checksum_boolean
#define CHECKSUM_IF(x) if( ~(checksum_boolean >> x) & 1) \
                    {                                               \
                        checksum_boolean |= 1 << x;
#define CHECKSUM_END }1

The 1 at the end is to force the user to put semi-colon at the end. In my compiler this is allowed.


The problem is figuring out how to do this without having the user to specify x (n bit to be checked). So he can use this:

CHECKSUM(char); // 7 run-once codes can be used

for( ; ; )
{
    CHECKSUM_IF
        // code..
    CHECKSUM_END;
}

Ideas how can I achieve this?


Answer:

I guess you're saying you want the macro to somehow automatically track which bit of your bitmask contains the flag for the current test. You could do it like this:

#define CHECKSUM(d) static d checksum_boolean; \
    d checksum_mask
#define CHECKSUM_START do { checksum_mask = 1; } while (0)
#define CHECKSUM_IF do {                       \
    if (!(checksum_boolean & checksum_mask)) { \
        checksum_boolean |= checksum_mask;
#define CHECKSUM_END                           \
    }                                          \
    checksum_mask <<= 1;                       \
} while (0)
#define CHECKSUM_RESET(i) do { checksum_boolean &= ~((uintmax_t) 1 << (i)); } while (0)

Which you might use like this:

CHECKSUM(char); // 7 run-once codes can be used

for( ; ; )
{
    CHECKSUM_START;
    CHECKSUM_IF
        // code..
    CHECKSUM_END;
    CHECKSUM_IF
        // other code..
    CHECKSUM_END;
}

Note, however, that that has severe limitations:

Those constraints arise because the preprocessor cannot count.

To put it another way, barring macro redefinitions, a macro without any arguments always expands to exactly the same text. Therefore, if you don't use a macro argument to indicate which flag bit applies in each case then that needs to be tracked at run time.


Related:


Does realloc() invalidate all pointers?


c,pointers,dynamic-memory-allocation,behavior,realloc
Note, this question is not asking if realloc() invalidates pointers within the original block, but if it invalidates all the other pointers. I'm new to C, and am a bit confused about the nature of realloc(), specifically if it moves any other memory. For example: void* ptr1 = malloc(2); void*...

Chance of a conditional occurring in Swift: Xcode


xcode,swift,if-statement,conditional,percentage
I am quite new to Xcode and swift so sorry if this is a bad description. Is there a way that there is a chance of your conditional occurring so instead of it happening 100% of the time when the conditions are met, it only happens 50% of the time...

Stop Prevent Default in else clause


if-statement,mobile,menu
Hello I have a mobile nav where some items have a subnav so I have set a preventDefault to stop these doing there normal actions and open the sub menu but some don't have a submenu ad now these don't work as normal. Any help would be great here is...

How do I check whether a file or file directory exist in bash?


bash,if-statement
I currently have this bash script (which is located in my home directory, i.e., /home/fusion809/ and I am running it as root as it's necessary for the icon copying lines): cd /home/fusion809/Pictures/Icon* declare -a A={Arch,Debian,Fedora,Mageia,Manjaro,OpenSUSE} declare -a B={Adwaita,Faenza,gnome,Humanity} for i in $A; do for j in $B; do if test...

Text justification C language


c,text,alignment
I have to solve a problem that involves left justification string length and leading zeros. I have the following table : BEGIN CLOSE CONCATENATE DELETE END INITIALIZE PRINT WRITE This is produced by a simple program. My problem is to find out how to convert it like that : It...

Array breaking in Pebble C


c,arrays,pebble-watch,cloudpebble
I'm trying to create a simple dice-rolling application in Pebble using C on CloudPebble. I have an array of different die sizes you can scroll through using Up/Down, and you roll (currently just generate a random number, it'll get fancier later) using the middle button. There's also a label at...

Segmentation fault with generating an RSA and saving in ASN.1/DER?


c,openssl,cryptography,rsa
#include <string.h> #include <openssl/aes.h> #include <openssl/rand.h> #include <openssl/bio.h> #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/pem.h> #define RSA_LEN 2048 #define RSA_FACTOR 65537 int genRSA2048(unsigned char **pub,unsigned int *pub_l,unsigned char **priv,unsigned int *priv_l){ RSA *pRSA = NULL; pRSA = RSA_generate_key(RSA_LEN,RSA_FACTOR,NULL,NULL); if (pRSA){ pub_l = malloc(sizeof(pub_l)); *pub_l = i2d_RSAPublicKey(pRSA,pub); priv_l = malloc(sizeof(priv_l));...

Is there Predefined-Macros define about byte order in armcc


c,armcc,predefined-macro
Is there Predefined-Macros define about byte order in armcc. I am a novice on the armcc.and sorry for my English. In gcc these are macros: __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__ __ORDER_BIG_ENDIAN__ __ORDER_PDP_ENDIAN__ ... Now I have to use armcc, Is there same like these with armcc? Thank a lot. by the way,the armcc...

How to read string until two consecutive spaces?


c,format,sscanf,c-strings
A well known function of the scanf() functions is that you can pass a format to scan input according to this format. For my case, I cannot seem to find a solution searching this and this documentation. I have a string (sInput) as the following: #something VAR1 this is a...

How does this code print odd and even?


c,if-statement,macros,logic
#define MACRO(num, str) {\ printf("%d", num);\ printf(" is");\ printf(" %s number", str);\ printf("\n");\ } int main(void) { int num; printf("Enter a number: "); scanf("%d", &num); if (num & 1) { MACRO(num, "Odd"); } else { MACRO(num, "Even"); } return 0; } Please explain the above code (if/else condition and how...

Galois LFSR - how to specify the output bit number


c,prng,shift-register
I am trying to understand how change the galois LFSR code to be able to specify the output bit number as a parameter for the function mentioned below. I mean I need to return not the last bit of LFSR as output bit, but any bit of the LFSR (...

Set precision dynamically using sprintf


c,printf,format-string
Using sprintf and the general syntax "%A.B" I can do this: double a = 0.0000005l; char myNumber[50]; sprintf(myNumber,"%.2lf",a); Can I set A and B dynamically in the format string?...

If statement for search field in Rails


jquery,ruby-on-rails,search,if-statement
I have a blog site and recently added a search bar for visitors to browse through blog posts. When used, all of the posts go away in the directory and only those which return via the search appear. In order to show the general directory and view all, I would...

Does strlen() always correctly report the number of char's in a pointer initialized string?


c,strlen
As long as I use the char and not some wchar_t type to declare a string will strlen() correctly report the number of chars in the string or are there some very specific cases I need to be aware of? Here is an example: char *something = "Report all my...

Java dice roll with unexpected random number


java,if-statement
I've written a simple Java program to display the results of 20 dice rolls on the console. The results I'm getting are listed below: 3 1 [email protected] 1 5 4 1 [email protected] 1 [email protected] [email protected] 1 6 [email protected] 1 [email protected] [email protected] 1 2 3 3 When I ran it for...

Counting bytes received by posix read()


c,function,serial-port,posix
I get confused with one line of code: temp_uart_count = read(VCOM, temp_uart_data, 4096); I found more about read function at http://linux.die.net/man/3/read, but if everything is okay it returns 0, so how we can get num of bytes received from that? temp_uart_count is used to count how much bytes we received...

Is post-increment operator guaranteed to run instantly?


c,c89,post-increment,ansi-c
Let's say I have the following code: int i = 0; func(i++, i++); The increment is happening right after returning the value? Is it guaranteed that the first argument will be 0, and the second argument will be 1?...

python if statement inside for syntax error


python,if-statement,syntax-error
I wrote some code but I can't get why the pyscripter is telling a syntax error in the if statement: #search for 9 elements file_writer = open('C:\\PythonProject2\\commands_NUM.txt','w') for item in data_indices: flag= search_object(item,data,obj_value_min,obj_value_max) if flag = True:###ERROR file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n') ##Here is the syntax...

Reverse ^ operator for decryption


c,algorithm,security,math,encryption
I'm trying to reverse the following code in order to provide a function which takes the buffer and decrypts it. void crypt_buffer(unsigned char *buffer, size_t size, char *key) { size_t i; int j; j = 0; for(i = 0; i < size; i++) { if(j >= KEY_SIZE) j = 0;...

C binary tree sort - extending it


c,binary-tree,binary-search-tree
I need some help in C Help me to extend the binary tree sort on C. I need to return a sorted array in sort function. here it is: #include <stdio.h> #include <stdlib.h> struct btreenode { struct btreenode *leftchild ; int data ; struct btreenode *rightchild ; } ; void...

free causing different results from malloc


c,string,malloc,free
Below is a C program i have written to print different combination of characters in a string. This is not an efficient way as this algorithm creats a lot of extra strings. However my question is NOT about how to solve this problem more efficiently. The program works(inefficiently though) and...

How does ((a++,b)) work? [duplicate]


c,function,recursion,comma
This question already has an answer here: What does the comma operator `,` do in C? 8 answers In the below block of code, I am trying to understand how the line return reverse((i++, i)) is working. #include <stdio.h> void reverse(int i); int main() { reverse(1); } void reverse(int...

C programming - Confusion regarding curly braces


c,scope
The following code is for replacing multiple consecutive spaces into 1 space. Although I manage to do it, I am confused in the use of curly braces. This one is actually running fine: #include <stdio.h> #include <stdlib.h> int main() { int ch, lastch; lastch = 'a'; while((ch = getchar())!= EOF)...

What does `strcpy(x+1, SEQX)` do?


c,strcpy
I'm wondering what this syntax of strcpy() does in line 65 and 66: 24 #define SEQX "TTCATA" 25 #define SEQY "TGCTCGTA" 61 M = strlen(SEQX); 62 N = strlen(SEQY); 63 x = malloc(sizeof(char) * (M+2)); /* +2: leading blank, and trailing \0 */ 64 y = malloc(sizeof(char) * (N+2)); 65...

OpenGL glTexImage2D memory issue


c,opengl
I'm loading a cubemap to create a skybox, everything is fine and the skybox renders properly with a correct texture application. However, I decided to check my program safety with valgrind, Valgrind gives this error: http://pastebin.com/seqmXjyx The line 53 in sky.c is: glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, texture.width, texture.height, 0,...

CGO converting Xlib XEvent struct to byte array?


c,go,xlib,cgo
I am creating a simple window manager (code based of the c code in tinywm) in Golang. To use Xlib, I am using cgo, so my header is: // #cgo LDFLAGS: -lX11 // #include <X11/Xlib.h> And I have a variable declaration, like: event := C.XEvent{} And then, I use this...

VS2012 Identifer not found when part of static lib


c,visual-studio-2012,linker,static-libraries
Using VS2012 C/C++: I created and linked a static lib called "libtools" to my project. Calls to functions in the libtools lib worked as expected. I created and linked a second static lib called "shunt" to my project. But when I incorporate a call to a function in shunt, I...

scanf get multiple values at once


c,char,segmentation-fault,user-input,scanf
I need to get in one single shot different inputs from one single line. In particular I need to get a single char and then, depending on which char value I just read, it can be a string and an int or a string, an int and another string and...

R: recursive function to give groups of consecutive numbers


r,if-statement,recursion,vector,integer
Given a sorted vector x: x <- c(1,2,4,6,7,10,11,12,15) I am trying to write a small function that will yield a similar sized vector y giving the last consecutive integer in order to group consecutive numbers. In my case it is (defining groups 2, 4, 7, 12 and 15): > y...

How to control C Macro Precedence


c,macros
#define VAL1CHK 20 #define NUM 1 #define JOIN(A,B,C) A##B##C int x = JOIN(VAL,NUM,CHK); With above code my expectation was int x = 20; But i get compilation error as macro expands to int x = VALNUMCHK; // Which is undefined How to make it so that NUM is replaced first...

C++ / C #define macro calculation


c++,c,macros
Suppose I have #define DETUNE1 sqrt(7)-sqrt(5) #define DETUNE2 sqrt(11)-sqrt(7) And I call these multiple times in my program. Are DETUNE1 and DETUNE2 calculated every time it is called? Thanks. Please don't downvote this, I really want to know and a search didn't turn up anything definite. ...

jQuery - clearInterval seems not to work


jquery,if-statement,intervals,clearinterval
Long story short: If the interval count exceeds 5 the code should clear the interval, stopping it from executing the function every second. But this doesn't seem to work. HTML <div id='feedback'></div> JavaScript / jQuery window.intervalcount = 0; var interval = setInterval(function () { intervalcount += 1; $("#feedback").text(intervalcount); }, 1000);...

Disadvantages of calling realloc in a loop


c,memory-management,out-of-memory,realloc
I'm trying to implement some math algorithms in C on Windows 7, and I need to repeatedly increase size of my array. Sometimes it fails because realloc can't allocate memory. But if I allocate a lot of memory at once in the beginning it works fine. Is it a problem...

Loop through database table and compare user input


mysql,c
I am trying to loop through the rows in a MySql table and compare the data in a certain column to some user input using C. Currently my code looks like this: MYSQL *cxn = mysql_init(NULL); MYSQL_RES *result; unsigned int num_fields; unsigned int num_rows; char *query_string; MYSQL_ROW *row; if (mysql_real_connect(cxn,...

using if statements in tableau on a contains function


if-statement,contains,tableau
Say I have city populations for each state / city in the united states. I want to mark each city with over 2 million population as a big city. then if a state contains a "big city", i want to mark that state as a "big state". I made a...

Infinite loop with fread


c,arrays,loops,malloc,fread
I'm trying to allocate an array 64 bytes in size and then loop over the array indexes to put a read a byte each from the inputfile. but when I don't malloc() the array indexes, the loop stays in index0 (so each time it loops it replaces the content in...

If/else problems in python


python,if-statement
Ok, I'm gonna explain this as best I can. I am trying to make an if/else statement in python that basically informs the user if they put in the right age based on raw input, but I keep getting an error in terms of my if statement. Can I get...

How to increment the value of an unsigned char * (C)


c++,c,openssl,byte,sha1
I have a value stored as an unsigned char * (in C). This holds the SHA1 hash of a string. My goal is to cover the SHA1 key space. Since I'm using <openssl/evp.h> to generate the hashes, I end up with an unsigned char* holding the SHA1 value. Now I...

Passing int using char pointer in C


c,exec,ipc
I'm trying to figure out how to pass an int using a char pointer. It fails once the int value is too large for the char. This is what I'm trying to figure out: char *args[5]; int i = 20; /*some other code/assignments*/ args[2] = (char *)&i; execv(path, args); How...

CallXXXMethod undefined using JNI in C


java,c,jni
So I've tried to use the JNI interface to call Java methods from C. Calling static methods is no problem, but I get stuck when I want to call a method on an object. The code is as follows: #include <stdio.h> #include <string.h> #include <jni.h> int main() { JavaVMOption options[1];...

Segmentation Fault if I don't say int i=0


c,arrays,segmentation-fault,initialization,int
void removeVowels(char* array){ int i,j,v; i=0; char vowel[]={'a','e','i','o','u'}; while(array[i]!='\0') { for(v=0;v<5;v++) { if (array[i]==vowel[v]) { j=i; while(array[j]!='\0') { array[j]=array[j+1]; j++; } i--; break; } } i++; } } in function removeVowels() if I don't include i=0; and just say int i; why does it give segmentation fault? Isn't it automatically...

Stopping condition on a recursive function - Haskell


string,function,haskell,if-statement,recursion
So, I have this function which aims to align the text on the left without cutting words(only white spaces). However my problem is that I cannot find a stopping condition of the function and it goes infinitely. f n "" = "" --weak condition f n s = if n...

The if statement doesn't work for false in php


php,if-statement
When trying to get familiar with if statement in PHP, this happened. First time i tried this code below. if(true) {echo 'true';} else {echo 'false';} And the output was true when the condition is true. Again, when the condition is false (if(false)) it echos false. But i tried the same,...

The program after if statement is not exectuing


python,if-statement
I have a problem with escaping from if, my code looks more or less like this in python: if answear == "Yes": do something pylab.show() if anwear == "No": do something pylab.show() answear2= input("How are you?") print ("I'm here") The problem is that is statement works nicely but after showing...

Comparing cell contents against string in Excel


string,excel,if-statement,comparison
Following is my table file:*.css file:*.csS file:*.PDF file:*.PDF file:*.ppt file:*.xls file:*.xls file:*.doc file:*.doc file:*.CFM file:*.dot file:*.cfc file:*.CFM file:*.CFC file:*.cfc file:*.DOC I need a formula to populate the H column with True or False if it finds column G in column F (exact case). I used following but nothing seems to...

Program to reverse a string in C without declaring a char[]


c,string,pointers,char
I need to reverse a given string and display it without using the value At[index] notation , I tried the below program using pointers,but it does not print anything for the reverse string, Please help! int main() { char* name=malloc(256); printf("\nEnter string\n"); scanf("%s",name); printf("\nYou entered%s",name); int i,count; count=0; //find the...

Display only values containing specific word in array


php,arrays,json,string,if-statement
Right now I am working on a search function for my json decoded results. The code that I got looks like this: <?php foreach($soeg_decoded as $key => $val){ $value = $val["Value"]; $seotitle = $val["SEOTitle"]; $text = $val["Text"]; echo '<tr><td>' . $value . '</td><td>' . $seotitle . '</td><td>' . $text ....

getchar() not working in c


c,while-loop,char,scanf,getchar
getchar() is not working in the below program, can anyone help me to solve this out. I tried scanf() function in place of getchar() then also it is not working. I am not able to figure out the root cause of the issue, can anyone please help me. #include<stdio.h> int...

How to make nested IF statements neater


python,if-statement
This question could be asked in a language independent way but I'm asking in the context of python since different languages will have different nuances. I recognize that this is similar to this question but I think mine is different in that I'm asking about a case where putting the...