Does C have a concatenation operator? - c

This Verilog tutorial (see the table at the end) suggests that { } is a concatenation operator is C. I don't remember curly brackets as being an operator in C.
Is { } a concatenation operator in C?

No, that's just nonsense. No idea what that's about.

From the linked tutorial:
To make life easier for us, nearly all operators (at least the ones in the list below) are exactly the same as their counterparts in the C programming language.
Emphasis mine. The exceptions are ~&, ~|, ~^, ^~, and {}.
Adjacent string literals are automatically concatenated:
char *str = "This is the first half "
"and this is the second half";
Anything involving a char buffer, though, requires a library function like strcat:
char buf[SOME_SIZE];
...
strcat(buf, "This is the first half ");
strcat(buf, "and this is the second half");
There is also the preprocessor token pasting operator ##, but the result must be a valid preprocessor token.

Absolutely not. The curly braces in C as C++, C# and others delimit a block of code. It's an error on their site. There is neither the possibility of operator overloading since we talk of 'pure, old fashioned C programming language'

The only operator C has with { } is the ( ){ } operator which is the compound literal operator.

No, in pure C, the braces are not a concatenation operator.
Note that the table of operators on the Verilog page includes a number of other 'non-C, non-C++' operators:
~& nand
| or
~| nor
^ xor
^~ xnor
~^ xnor
Where the operators are the same as in C, they have the same meaning as in C. But there are operators in Verilog that are not in C (and, if that table is complete, operators in C that are not in Verilog).

Depends. Curly brackets are not an operator by definition in C, and they do not concatenate strings. But they group statements and introduce new blocks. Maybe this is what the author meant. But however, it is at least inaccurate if not wrong.

## is a concatenation operator....

Related

c - if + else if + else in one line? [duplicate]

This question already has answers here:
Yet Another Conditional Operator Nesting Question
(2 answers)
Why is the conditional operator right associative?
(3 answers)
To ternary or not to ternary? [closed]
(54 answers)
Closed 5 years ago.
I just got a question idea after having misunderstood a friend's statement.
My friend told me: I just taught a colleague how to do a if/else in one line in c.
Example:
int i = 0;
i < 0 ? printf("i is below 0") : printf("i is over or equal to 0");
For now, nothing new, it's called a ternary and most people know about that kind of statement BUT I first understood that:
I just taught a colleague how to do a IF / ELSE IF / ELSE in one line.
Since I don't / didn't know that doing such a thing is possible I tried to do something like
int i = 0;
i < 0 ? printf("i is below 0") : i == 0 ? printf("i equal 0") : printf("i is over 0");
Is it actually possible to do a if / else if / else "ternary". Or is there a way to do such a thing without having an horrible piece of code?
If you see e.g. this conditional expression reference you can see that the format of a "ternary expression" is
condition ? expression-true : expression-false
All three parts of the conditional expressions are, in turn, expressions. That means you can have almost any kind of expression, including nested conditional (ternary) expressions in them.
It should be noted that conditional expressions might make the code harder to read and understand, especially if used badly or if one attempt to put too much logic and nesting into the expressions.
This is definitely valid.
Or you could try something like this -
printf(i < 0 ? "i is below 0" : i == 0 ? "i equal 0" : "i is over 0");
C has both statements and expressions. There are two different kinds of syntactical things. BTW lines don't matter much in C (except for the preprocessor).
Expressions (like f(1,x+y) or even x=y++) are a special kind of statements (the most common one).
As an extension to C, the GCC compiler adds statement expressions, beyond what the C11 standard (read n1570) defines. Please download then read that n1570 repoort.
if is for conditional statements but the ternary ?: operator is for expressions (with all three operands being sub-expressions).
Some programming languages (notably Lisp, Haskell, Scheme, Ocaml) have only expressions and don't have any statements.

Using symbols read by scanf() as C operators

I want to read a symbol in from scanf() and then get C to use it for what it is. My current (relevant) piece of code looks like:
float a; /* First Number */
char sym; /* Symbol (i.e. +, -, /, *) */
float b; /* Second number.... */
puts("Please type your equation");
printf("$: ");
scanf("%f %c %f", &a, &sym, &b);
So if the user were to type (at the $: prompt) 5 + 10 then the program should proceed to evaluate 5 + 10 but I know I can't expect C to do this (not without working some magic first :) because '+' is just an ANSI character code, so what I'm asking is:
How do I get C to literally take the variable sym for what we (as people) take it as (a plus +) and then use that to solve the equation as if the variables had hard-coded values?
EDIT
I now understand that it may be impossible (see comment by SLaks), so any workarounds would be great!
Just as a side-note: I know I can use
....
add(int a, int b)
{
return (1 + b);
}
....
if (sym == '+') {
add(a, b);
}
and so on, but when the I get to including more then just a and b (e.g. a, sym, b, sym2, c) and the user has more than a single type of operator (e.g. 2 + 4 - 6) this becomes tedious and time consuming.
You can't really do that. C is a compiled language (so is C++) and you cannot just execute a string as if it is C code at run time. The instructions are generated when the code is compiled. Other languages like Python which are interpreted support this (such as the eval function in Python). Using the if statements is probably the most efficient approach.
Also like Jiang Jie said I would look into reverse polish notation. This involves using a stack to evaluate the mathematical expressions and can handle complex expressions.
You will also probably need to look into converting infix expressions (e.g. 1 + 2) into postfix expressions (1 2 +).
If you really want to learn C by interpreting it, then as you'll need a tokenizer, a parser and an expression tree evaluator. I know there are the old classics: LEX and YACC, but I'm pretty sure there are newer tokenizers and parser generators. You can google for "C parser generator". There's even a Wikipedia article comparing a bunch of them.
But I will say that writing a C interpreter is not the best way to learn C. Learning to write simpler programs is highly recommended. I suggest finding a tutorial site or getting a book. There are lots of both.
What you need is Reverse Polish Notation, let the user input a regular math expression, then you need to transform it into an RPN expression, then calculate.

Checking Valid Arithmetic Expression in Lex (in C)

I have to write code for checking if an arithmetic expression is valid or not , in lex. I am aware that I could do this very easily using yacc but doing only in lex is not so easy.
I have written the code below, which for some reason doesn't work.
Besides this, i also don't get how to handle binary operators .
My wrong code:
%{
#include <stdio.h>
/* Will be using stack to check the validity of arithetic expressions */
char stack[100];
int top = 0;
int validity =0;S
%}
operand [a-zA-Z0-9_]+
%%
/* Will consider unary operators (++,--), binary operators(+,-,*,/,^), braces((,)) and assignment operators (=,+=,-=,*=,^=) */
"(" { stack[top++]='(';}
")" { if(stack[top]!=')') yerror(); else top--;}
[+|"-"|*|/|^|%] { if(stack[top]!='$') yerror(); else stack[top]=='&';}
"++" { if(stack[top]!='$') yerror(); else top--;}
[+"-"*^%]?= { if(top) yerror();}
operand { if(stack[top]=='&') top--; else stack[top++]='$';}
%%
int yerror()
{
printf("Invalid Arithmetic Expression\n");
}
First, learn how to write regular expressions in Flex. (Patterns, Flex manual).
Inside a character class ([…]), neither quotes nor stars nor vertical bars are special. To include a - or a ], you can escape them with a \ or put them at the beginning of the list, or in the case of - at the end.
So in:
[+|"-"|*|/|^|%]
The | is just another character in the list, and including it five times doesn't change anything. "-" is a character range consisting only of the character ", although I suppose the intention was to include a -. Probably you wanted [-+*/^%] or [+\-*/^%].
There is no way that the flex scanner can guess that a + (for example) is a unary operator instead of a binary operator, and putting it twice in the list of rules won't do anything; the first rule will always take effect.
Finally, if you use definitions (like operand) in your patterns, you have to enclose them in braces: {operand}; otherwise, flex will interpret it as a simple keyword.
And a hint for the assignment itself: A valid unparenthesized arithmetic expression can be simplified into the regular expression:
term {prefix-operator}*{operand}{postfix-operator}*
expr {term}({infix-operator}{term})*
But you can't use that directly because (a) it doesn't deal with parentheses, (b) you probably need to allow whitespace, and (c) it doesn't correctly reject a+++++b because C insists on the "maximal munch" rule for lexical scans, so that is not the same as the correct expression a++ + ++b.
You can, however, translate the above regular expression into a very simple two-state state machine.

Conditional statements inside `printf`

Is there any method to use a conditional statement inside other statements, for example printf?
One way is using ternary operator ? : eg:
printf("%d", a < b ? a : b);
Is there a method for more complicated conditions?
There is no need for more complex expressions, the conditional operator is already bad enough. There is no language feature for it. Instead, write a function.
printf("%d", compare(a,b)); // good programming, readable code
printf("%d", a<b?(x<y?x:y):(x<y?y:x)); // bad programming, unreadable mess
Every conditional statement return 1 or 0. These values are int
So if you do printf("%d",a>b); then either 1(true) or 0(false) will be printed.
In your example you are using ternary operator a<b?a:b.
If condition is true then a will be printed else b.
You cannot put statements into printf at all, you only can put expressions there. The ternary operator forms an expression. An expression is basically a tree of operators and operands, however there are a few funny operators allowed, like the ',' comma operator or the '=' assignment operator. This allows expressions to have side effects.

Compound literals and function-like macros: bug in gcc or the C standard?

In C99, we have compound literals, and they can be passed to functions as in:
f((int[2]){ 1, 2 });
However, if f is not a function but rather a function-like macro, gcc barfs on this due to the preprocessor parsing it not as one argument but as two arguments, "(int[2]){ 1" and "2 }".
Is this a bug in gcc or in the C standard? If it's the latter, that pretty much rules out all transparent use of function-like macros, which seems like a huge defect...
Edit: As an example, one would expect the following to be a conforming program fragment:
fgetc((FILE *[2]){ f1, f2 }[i]);
But since fgetc could be implemented as a macro (albeit being required to protect its argument and not evaluate it more than once), this code would actually be incorrect. That seems surprising to me.
This "bug" has existed in the standard since C89:
#include <stdio.h>
void function(int a) {
printf("%d\n", a);
}
#define macro(a) do { printf("%d\n", a); } while (0)
int main() {
function(1 ? 1, 2: 3); /* comma operator */
macro(1 ? 1, 2: 3); /* macro argument separator - invalid code */
return 0;
}
I haven't actually looked through the standard to check this parse, I've taken gcc's word for it, but informally the need for a matching : to each ? trumps both operator precedence and argument list syntax to make the first statement work. No such luck with the second.
This is per the C Standard, similar to how in C++, the following is a problem:
f(ClassTemplate<X, Y>) // f gets two arguments: 'ClassTemplate<X' and 'Y>'
If it is legal to add some extra parentheses there in C99, you can use:
f(((int[2]){ 1, 2 }));
^ ^
The rule specifying this behavior, from C99 §6.10.3/11, is as follows:
The sequence of preprocessing tokens bounded by the outside-most matching parentheses
forms the list of arguments for the function-like macro.
The individual arguments within the list are separated by comma preprocessing tokens, but comma preprocessing tokens between matching inner parentheses do not separate arguments.
To the extent that it's a bug at all, it's with the standard, not gcc (i.e., in this respect I believe gcc is doing what the standard requires).

Resources