Thread: #define thing in C

  1. #1
    Registered User
    Join Date
    Nov 2015
    Posts
    30

    #define thing in C

    Hello,
    Im novice in programming, i made a search on it but i couldnt understand why this code outputs 8?

    Code:
    #include <stdio.h>
    #define Z 7 + 3
    int main (void){
        
        int a = Z / 2;
         printf("%d", a);
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    Code:
    $ gcc -E foo.c
    <<< snipped a lot of expanded stdio.h
    int main (void){
    
      int a = 7 + 3 / 2;
      printf("%d", a);
    }
    You see, your Z just expands to 7 + 3

    Then operator precedence takes over.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2015
    Posts
    30
    That's cool, so do not evaluate first like me Thank you a lot.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Your takeaway here should actually be that parentheses should be used for such macros, e.g.,
    Code:
    #define Z (7 + 3)
    though of course in this specific case you might just write:
    Code:
    #define Z 10
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. difference between #define and #define ()
    By bored_guy in forum C Programming
    Replies: 8
    Last Post: 07-20-2009, 06:58 PM
  2. If it's not one thing...
    By cboard_member in forum A Brief History of Cprogramming.com
    Replies: 11
    Last Post: 11-20-2006, 11:39 AM
  3. WEb thing!
    By Jenny Tey in forum Tech Board
    Replies: 18
    Last Post: 05-23-2003, 08:38 AM
  4. One more thing
    By aba_abstract2k in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2002, 10:57 PM
  5. Is FAA doing the right thing?
    By Barjor in forum A Brief History of Cprogramming.com
    Replies: 8
    Last Post: 04-30-2002, 03:57 AM