Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the problem with putting brackets("(") in a printf code

Tags:

c

printf

I've just started C-Programming and have a question on the following code.

#include <stdio.h>

int main(void)
{
    int num1, num2, num3;
    int result;

        printf("(num1 - num2) x (num2 + num3) x (num3 % num1) \n");
    printf("Insert 3 numbers: ");
    scanf("%d %d %d", &num1, &num2, &num3);

    result = (num1 - num2) * (num2 + num3) * (num3 % num1);
    printf("Answer: %d ", result);
    return 0;
}

An Error occurs whenever I put the following single line of code:

  printf("(num1 - num2) x (num2 + num3) x (num3 % num1) \n");

The reason I put this in was because I wanted to print this equation, but an error occurs whenever I put this in. The error message seems to say that there is a problem in the usage of brackets, but I don't get why putting brackets becomes a problem.

I expect the output to be,

  (num1 - num2) x (num2 + num3) x (num3 % num1)
  Insert 3 numbers: 

But the Following Error occurs:

"Debug Assertion Failed"

...

Expression: "("'n' format specifier disabled",')

like image 381
Learner_15 Avatar asked Dec 22 '22 23:12

Learner_15


1 Answers

It's not about the parenthesis, it's about the %. For printf() format string, % character has a special meaning.

From C11, chapter §7.21.6.1

[...] The format is composed of zero or more directives: ordinary multibyte characters (not %), which are copied unchanged to the output stream; and conversion specifications, each of which results in fetching zero or more subsequent arguments, converting them, if applicable, according to the corresponding conversion specifier, and then writing the result to the output stream.

and

Each conversion specification is introduced by the character %. [...]

So, to print a % character itself, you need to put another % as the conversion specifier. From the list of conversion specifiers, (paragraph 8 in the same spec)

% A % character is written. No argument is converted. The complete conversion specification shall be %%.

like image 102
Sourav Ghosh Avatar answered Dec 28 '22 06:12

Sourav Ghosh