Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On understanding how printf("%d\n", ( { int n; scanf("%d", &n); n*n; } )); works in C

Tags:

c

printf

block

I came across this program via a quora answer

 #include<stdio.h>
 int main() {
    printf("%d\n", ( { int n; scanf("%d", &n); n*n; } ));
    return 0;
 }

I was wondering how does this work and if this conforms the standard?

like image 256
Quixotic Avatar asked Apr 26 '13 15:04

Quixotic


People also ask

What is meaning of scanf %D &N?

scanf("%d",&n),n. The value of the condition is the value of the second operand of the comma operator that is of the variable n . If n is not equal to 0 then the loop is executed. You can imagine it the following way start: scanf("%d",&n); if ( n != 0 ) { //...

How does scanf() work in C?

Description. The scanf() function reads data from the standard input stream stdin into the locations given by each entry in argument-list. Each argument must be a pointer to a variable with a type that corresponds to a type specifier in format-string.

Why is scanf used?

In C programming, scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards.

Why we use& in scanf?

scanf requires the addressOf operator (&) because it takes a pointer as an argument. Therefore in order to pass in a variable to be set to a passed in value you have to make a pointer out of the variable so that it can be changed.


1 Answers

This code is using a "GNU C" feature called statement-expressions, whereby a parentheses-enclosed compound statement can be used as an expression, whose type and value match the result of the last statement in the compound statement. This is not syntactically valid C, but a GCC feature (also adopted by some other compilers) that was added presumably because it was deemed important for writing macros which do not evaluate their arguments more than once.

You should be aware of what it is and what it does in case you encounter it in code you have to read, but I would avoid using it yourself. It's confusing, unnecessary, and non-standard. The same thing can almost always be achieved portably with static inline functions.

like image 178
R.. GitHub STOP HELPING ICE Avatar answered Oct 20 '22 22:10

R.. GitHub STOP HELPING ICE