Menu
  • HOME
  • TAGS

is return main(); a valid syntax?

Tag: c,function,return,language-lawyer,return-type

I found some interesting code lines:

#include <stdio.h>

int main()
{
    printf("Hi there");
    return main();
}

It compiles ok (VS2013) and ends up in stackoverflow error because of the recursive call to main(). I didn't know that the return statement accepts any parameter that can be evaluated to the expected return data type, in this example even int main().

Standard C or Microsoft-ish behaviour?

Best How To :

I didn't know that the return statement accepts any parameter that can be evaluated to the expected return data type,

Well, a return statement can have an expression.

Quoting C11 standard, chapter 6.8.6.4, The return statement.

If a return statement with an expression is executed, the value of the expression is returned to the caller as the value of the function call expression.

so, in case of return main();, the main(); function call is the expression.

And regarding the behaviour of return main();, this behaves like a normal recursive function, the exception being an infinite recursion in this case.

Standard C or Microsoft-ish behaviour?

As long as C standard is considered, it does not impose any restriction upon calling main() recursively.

However, FWIW, AFAIK, in C++, it is not allowed.

How to control C Macro Precedence

c,macros

You can redirect the JOIN operation to another macro, which then does the actual pasting, in order to enforce expansion of its arguments: #define VAL1CHK 20 #define NUM 1 #define JOIN1(A, B, C) A##B##C #define JOIN(A, B, C) JOIN1(A, B, C) int x = JOIN(VAL,NUM,CHK); This technique is often used...

CGO converting Xlib XEvent struct to byte array?

c,go,xlib,cgo

As mentioned in the cgo documentation: As Go doesn't have support for C's union type in the general case, C's union types are represented as a Go byte array with the same length. Another SO question: Golang CGo: converting union field to Go type or a go-nuts mailing list post...

Galois LFSR - how to specify the output bit number

c,prng,shift-register

If you need bit k (k = 0 ..15), you can do the following: return (lfsr >> k) & 1; This shifts the register kbit positions to the right and masks the least significant bit....

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

c,openssl,cryptography,rsa

pub_l = malloc(sizeof(pub_l)); is simply not needed. Nor is priv_l = malloc(sizeof(priv_l));. Remove them both from your function. You should be populating your out-parameters; instead you're throwing out the caller's provided addresses to populate and (a) populating your own, then (b) leaking the memory you just allocated. The result is...

JSLint won't recognize getElementById

javascript,function,getelementbyid,jslint

You missed document prefix. As getElementById is defined on document object you've to call it using document object as follow: document.getElementById("player").play(); // ^^^^^^ Docs...

C binary tree sort - extending it

c,binary-tree,binary-search-tree

a sample to modify like as void inorder ( struct btreenode *, int ** ) ; int* sort(int *array, int arr_size) { struct btreenode *bt = NULL; int i, *p = array; for ( i = 0 ; i < arr_size ; i++ ) insert ( &bt, array[i] ) ;...

Stopping condition on a recursive function - Haskell

string,function,haskell,if-statement,recursion

Your code doesn't handle the case where a line is shorter than the maximum length. This is somewhat obscured by another bug: n is decremented until a whitespace is found, and then f is called recursively passing this decremented value of n, effectively limiting all subsequent lines to the length...

Replace paragraph in HTML with new paragraph using Javascript

javascript,function,onload,getelementbyid,appendchild

You can just replace the text content of the #two element: var two = document.getElementById("two"); window.onload = function () { var t = "I am the superior text"; two.textContent = t; }; <p id="two">Lorem ipsum dolor sit amet.</p> If you use createTextNode, then you'll need to use two.textContent = t.textContent...

Does realloc() invalidate all pointers?

c,pointers,dynamic-memory-allocation,behavior,realloc

Yes, ptr2 is unaffected by realloc(), it has no connection to realloc() call whatsoever(as per the current code). However, FWIW, as per the man page of realloc(), (emphasis mine) The realloc() function returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and...

Stuck on Structs(c++)

c++,function,struct

You have declared coordinate startPt, endPt; in main() and you are trying to access them Readcoordinate(). To resolve error you should declarecoordinate startPt, endPt;inReadcoordinate()` or pass them as argument. coordinate Readcoordinate() { coordinate startPt; cout << "Enter Longitude(in degrees)" << endl; cin >> startPt.latitude >> startPt.longitude >> startPt.city; return startPt;...

C++ need help figuring out word count in function. (Ex. Hello World = 2)

c++,function

int wordCounter(char usStr[]) { int index= sizeof(usStr); int result = 0; for (int i=0; i<index; i++){ if(usStr[index]== ' ') result++; }//end of the loop return result+1; } //try this one. ...

Passing int using char pointer in C

c,exec,ipc

Programs simply do not take integers as arguments, they take strings. Those strings can be decimal representations of integers, but they are still strings. So you are asking how to do something that simply doesn't make any sense. Twenty is an integer. It's the number of things you have if...

Disadvantages of calling realloc in a loop

c,memory-management,out-of-memory,realloc

When you allocate/deallocate memory many times, it may create fragmentation in the memory and you may not get big contiguous chunk of the memory. When you do a realloc, some extra memory may be needed for a short period of time to move the data. If your algorithm does...

Array breaking in Pebble C

c,arrays,pebble-watch,cloudpebble

The problem is this line static char *die_label = "D"; That points die_label to a region of memory that a) should not be written to, and b) only has space for two characters, the D and the \0 terminator. So the strcat is writing into memory that it shouldn't be....

How to read string until two consecutive spaces?

c,format,sscanf,c-strings

The scanf family of functions are good for simple parsing, but not for more complicated things like you seem to do. You could probably solve it by using e.g. strstr to find the comment starter "//", terminate the string there, and then remove trailing space....

Selecting and removing a html select option without selecting by index or ID, using vanilla JavaScript

javascript,function,select,options

Something like this? (function (){ var parent = document.getElementById("MediaCategory"); for(var i=0; i< parent.children.length; i++){ var child = parent.children[i]; if(child.text === "Archive") { parent.removeChild(child); } } })(); ...

Loop through database table and compare user input

mysql,c

If you are only looking for fields that match the input, you'll want to search the database using the input string. In other words, write your query string so that it only gives you results that match the user input. This will be much faster than searching through every returned...

CallXXXMethod undefined using JNI in C

java,c,jni

There are few fixes required in the code: CallIntMethod should be (*env)->CallIntMethod class Test should be public Invocation should be jint age = (*env)->CallIntMethod(env, mod_obj, mid, NULL); Note that you need class name to call a static function but an object to call a method. (cls2 -> person) mid =...

C++ / C #define macro calculation

c++,c,macros

Are DETUNE1 and DETUNE2 calculated every time it is called? Very unlikely. Because you are calling sqrt with constants, most compilers would optimize the call to the sqrt functions and replace it with a constant value. GCC does that at -O1. So does clang. (See live). In the general...

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

c,string,pointers,char

Important: scanf(" %s", name); has no bounds checking on the input. If someone enters more than 255 characters into your program, it may give undefined behaviour. Now, you have the char array you have the count (number of char in the array), why do you need to bother doing stuffs...

VS2012 Identifer not found when part of static lib

c,visual-studio-2012,linker,static-libraries

C++ uses something called name mangling when it creates symbol names. It's needed because the symbol names must contain the complete function signature. When you use extern "C" the names will not be mangled, and can be used from other programming languages, like C. You clearly make the shunt library...

getchar() not working in c

c,while-loop,char,scanf,getchar

That's because scanf() left the trailing newline in input. I suggest replacing this: ch = getchar(); With: scanf(" %c", &ch); Note the leading space in the format string. It is needed to force scanf() to ignore every whitespace character until a non-whitespace is read. This is generally more robust than...

Is there Predefined-Macros define about byte order in armcc

c,armcc,predefined-macro

Well according to this page: http://www.keil.com/support/man/docs/armccref/armccref_BABJFEFG.htm You have __BIG_ENDIAN which is defined when compiling for a big endian target....

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

c,strcpy

The pointer + offset notation is used as a convenient means to reference memory locations. In your case, the pointer is provided by malloc() after allocating sufficient heap memory, and represents an array of M + 2 elements of type char, thus the notation as used in your code represents...

C programming - Confusion regarding curly braces

c,scope

The only difference between the two is the scope of the else. Without the braces, it spans until the end of the full statement, which is the next ;, i.e the next line: else putchar(ch); /* end of else */ lastch = ch; /* outside of if-else */ With the...

Update input number variable onclick

javascript,jquery,html,function

You need to put all the calculations into the calc() function: function calc() { // Get Years var years = (document.getElementById('years').value); // Variables var years; var gallons = 1100 * 365; var grain = 45 * 365; var forest = 30 * 365; var co2 = 20 * 365; var...

Text justification C language

c,text,alignment

From printf's manual: The field width An optional decimal digit string (with nonzero first digit) specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given). Instead...

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

c++,c,openssl,byte,sha1

I am assuming your pointer refers to 20 bytes, for the 160 bit value. (An alternative may be text characters representing hex values for the same 160 bit meaning, but occupying more characters) You can declare a class for the data, and implement a method to increment the low order...

Can't understand this Javascript function (function overloading)

javascript,function,methods,overloading

fn.length will return the number of parameters defined in fn. Will arguments.length return the number of which arguments? The already existing function's? No. arguments is an array-like local variable that's available inside of a function. It contains the number of arguments passed to the function. The rest of your...

scanf get multiple values at once

c,char,segmentation-fault,user-input,scanf

I'm not saying that it cannot be done using scanf(), but IMHO, that's not the best way to do it. Instead, use fgets() to read the whole like, use strtok() to tokenize the input and then, based on the first token value, iterate over the input string as required. A...

PercentOfSum(fld, condfld) SSRS Equivalent

function,reporting-services,crystal-reports,ssrs-2008,ssrs-2008-r2

It's a tricky question because grouping in SSRS is handled outside of functions, so the equivalent to condfld is explained here. The short answer is the cell will generally obey the grouping that you have applied to the row. So onto the percent, you'll need an expression (right click on...

session value in javascript cannot be set

javascript,function,session

Javascript is a client-side language. Session are server-side component. If you want to update session when user does something on your page, you should create a ajax request to the server. Or maybe use some client side variables that, for some aspects, are similar to session (they will be forever...

Is it possible to use $(this) in a function called from another function?

jquery,function,this

Always be careful when using the this as you may end up using an unexpected value depending on the context your function was called. Instead, you should consider using a parameter: $('.member-div a').on("click",function(f){ f.preventDefault(); newfunc($(this)); }); function newfunc(item){ var x = item.parent('div').attr('id').slice(-1); $('.member-div').hide(); if(item.hasClass('next')){ var y = parseInt(x)+1; }; if(item.hasClass('back')){...

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

c,function,recursion,comma

In your first code, Case 1: return reverse(i++); will cause stack overflow as the value of unchanged i will be used as the function argument (as the effect of post increment will be sequenced after the function call), and then i will be increased. So, it is basically calling the...

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

c,arrays,segmentation-fault,initialization,int

In your code, int i is an automatic local variable. If not initialized explicitly, the value held by that variable in indeterministic. So, without explicit initialization, using (reading the value of ) i in any form, like array[i] invokes undefined behaviour, the side-effect being a segmentation fault. Isn't it automatically...

How can I minimize this function in R?

r,function,optimization,mathematical-optimization

I think you want to minimize the square of a-fptotal ... ff <- function(x) myfun(x)^2 > optimize(ff,lower=0,upper=30000) $minimum [1] 28356.39 $objective [1] 1.323489e-23 Or find the root (i.e. where myfun(x)==0): uniroot(myfun,interval=c(0,30000)) $root [1] 28356.39 $f.root [1] 1.482476e-08 $iter [1] 4 $init.it [1] NA $estim.prec [1] 6.103517e-05 ...

Infinite loop with fread

c,arrays,loops,malloc,fread

If you're "trying to allocate an array 64 bytes in size", you may consider uint8_t Buffer[64]; instead of uint8_t *Buffer[64]; (the latter is an array of 64 pointers to byte) After doing this, you will have no need in malloc as your structure with a 64 bytes array inside is...

Reverse ^ operator for decryption

c,algorithm,security,math,encryption

This is not a power operator. It is the XOR operator. The thing that you notice for the XOR operator is that x ^ k ^ k == x. That means that your encryption function is already the decryption function when called with the same key and the ciphertext instead...

jQuery - Value in Function

jquery,arrays,function

You need to use brackets notation to access property by variable: function myFunc( array, fieldToCompare, valueToCompare ) { if( array[fieldToCompare] == "Thiago" ) alert(true); } And wrap name in quotes: myFunc( myArray, 'name', "Thiago" ); ...

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

c,strlen

What strlen does is basically count all bytes until it hits a zero-byte, the so-called null-terminator, character '\0'. So as long as the string contains a terminator within the bounds of the memory allocated for the string, strlen will correctly return the number of char in the string. Note that...

SQL average age comparison function returns null

mysql,sql,function,datetime

While you declared the variable averMen, you have not initialized it. The query which should be calculating averMen is calculating averWomen instead. Try changing ... SELECT AVG(DATEDIFF(BIRTH_DATE,CURDATE())) INTO averWomen FROM PLAYERS WHERE sex = 'M'; into SELECT AVG(DATEDIFF(BIRTH_DATE,CURDATE())) INTO averMen FROM PLAYERS WHERE sex = 'M'; ...

Is post-increment operator guaranteed to run instantly?

c,c89,post-increment,ansi-c

This code is broken for two reasons: Accessing a variable twice between sequence points, for other purposes than to determine which value to store, is undefined behavior. There are no sequence points between the evaluation of function parameters. Meaning anything could happen, your program might crash & burn (or more...

Counting bytes received by posix read()

c,function,serial-port,posix

Yes, temp_uart_count will contain the actual number of bytes read, and obviously that number will be smaller or equal to the number of elements of temp_uart_data. If you get 0, it means that the end of file (or an equivalent condition) has been reached and there is nothing else to...

Set precision dynamically using sprintf

c,printf,format-string

Yes, you can do that. You need to use an asterisk * as the field width and .* as the precision. Then, you need to supply the arguments carrying the values. Something like sprintf(myNumber,"%*.*lf",A,B,a); Note: A and B need to be type int. From the C11 standard, chapter ยง7.21.6.1, fprintf()...

How does this code print odd and even?

c,if-statement,macros,logic

In binary any numbers LSB (Least Significant Bit) is set or 1 means the number is odd, and LSB 0 means the number is even. Lets take a look: Decimal binary 1 001 (odd) 2 010 (even) 3 011 (odd) 4 100 (even) 5 101 (odd) SO, the following line...

sum of Digits through Recursion

java,function,recursion,sum,digit

You aren't actually recursing. You've setup your base case, but when solving a problem recursively you should have code within the function that calls the function itself. So you're missing a line that calls sumDigits, with a smaller argument. Consider two important parts of a recursive soutlion: The base case....

free causing different results from malloc

c,string,malloc,free

Every time you are creating your string, you are not appending a null terminator, which causes the error. So change this: for(j=0; j<rem_len; j++) { if(j != i) { remaining_for_next[index_4_next] = remaining[j]; index_4_next++; } } to this: for(j=0; j<rem_len; j++) { if(j != i) { remaining_for_next[index_4_next] = remaining[j]; index_4_next++; }...

Calling function and passing arguments multiple times

python,function,loops

a,b,c = 1,2,3 while i<n: a,b,c = myfunction(a,b,c) i +=1 ...