Search code examples
cif-statementrealloc

Is declaring a pointer and assigning the result of a realloc to it as an if argument valid in C?


I am trying to implement the Dijkstra algorithm, and I first need to design a graph structure with variable number of nodes; in order to do so, I'll need to dynamically change the size of an array of structures, and I wanted to know if writing this :

if( !(struct s *a = (struct s *)realloc(some_pointer_to_s_struct, new_size*sizeof(struct s))) ) {
    return -1; //because that means my pointer is NULL
}
//do something

is correct in C, because according to this post : answer to a post on the subject it is.

However when I tried to change my code to match that pattern, I get plenty of error: expected ‘)’ before xxx and other errors of the sort... I thought that maybe I forgot to match a bracket or a parenthesis at first, but I spent a good 30 minutes reviewing my code, and that doesn't seem to be the issue.


Solution

  • That question is about C++ and not about C. In C it isn't possible.


    BTW your code isn't valid C++ either as it tries to use a negation on the declaration.